0

I am making an node js application and i have problem that eventhough i use await+async it will not do the thing. I need to call the first function and then the second one, but the second one is always called before the first one here is the code

index.js

router.get('/', async function(req, res) {
    if(req.isAuthenticated()) {
        await UserManagementToolObject.saveCharacterWithUser(req.user);

        var something = await UserManagementToolObject.test2();
        console.log(something);
        res.end();
    } else {
        res.send('<h1>Express OAuth Test</h1>' + '<a href="/auth/bnet">Login with Bnet</a>');
    }
});

UserManagementTool.js

async test2() {
        var cc = "ee";
        return cc;
    }
    async saveCharacterWithUser(user) {
        var that = this;
        var url = "https://eu.api.battle.net/wow/user/characters?access_token="+user.token;
        await request({
            url: url,
            json: true
        }, async function (error, response, body) {

            if (!error && response.statusCode === 200) {
                await that.deleteCharactersForUpdate(user.battletag);
                var Characters = [];

                for (var i = 0; i < body["characters"].length; i++) {
                    var RequestedCharacter = body["characters"][i];
                    Characters.push(await that.saveUserCharacters(RequestedCharacter,user.battletag));
                }

                var User = new UserModel({
                    _id: new mongoose.Types.ObjectId(),
                    id: user.id,
                    battletag: user.battletag,
                    provider: user.provider,
                    characters: Characters
                });
                await that.saveUser(User,Characters);
            }
        });
    }
kokoto13
  • 57
  • 1
  • 9
  • There are several functions above. Which is "the first one" (`UserManagementToolObject.saveCharacterWithUser`?) and which is "the second one" (`UserManagementToolObject.test1`?)? Also, why do you think the second is being called first? Also note that nothing in `saveCharacterWithUser` waits for the callback you're passing `request` to finish its work. – T.J. Crowder Dec 16 '17 at 20:36
  • 3
    `await` ONLY actually awaits an async operation if the value you are awaiting is a promise. You cannot do `await request()` and expect it to wait for the request operation to finish because `request()` does not return a promise. You could switch to using `request-promise()`. In general, you should NOT mix regular async callbacks with promise managed async operations. If you're going to use promises and `await`, then first switch all your async operations to ones that return promises and then you can use `await` and promise logic to control the flow. – jfriend00 Dec 16 '17 at 20:36
  • @jfriend00: It's a bit more complicated than that (you can `await` non-promise returning functions, but it's effectively `await Promise.resolve(theFunction())`), but indeed, the code above doesn't wait for `request`'s work to **finish**. – T.J. Crowder Dec 16 '17 at 20:38
  • @T.J.Crowder - The point is that it doesn't `await` the async operation which is what the OP expects and needs it to do. – jfriend00 Dec 16 '17 at 20:39
  • @jfriend00: Indeed not. There *has* to be a dupetarget for this... – T.J. Crowder Dec 16 '17 at 20:39
  • @T.J.Crowder - Yeah, I'm sure there's a dup for that single issue. Wasn't sure if that was the ONLY issue in this mess of a mix of callbacks, await and promises. – jfriend00 Dec 16 '17 at 20:40
  • As a start, what is the point of declaring the GET function `async`? We can also discuss the other ones. – RaphaMex Dec 16 '17 at 20:43
  • I have tried to console log both functions and the test2() is always called first – kokoto13 Dec 16 '17 at 20:44
  • The point is that i wouldnt be able to use await – kokoto13 Dec 16 '17 at 20:45
  • @T.J.Crowder I found [that](https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout) using [this search](https://stackoverflow.com/search?q=[js][async-await]+request+callback), what do you think? – Bergi Dec 16 '17 at 20:51
  • @Bergi: A bit tenuous to me (not least because of all the chaff in the question). Could it be we don't have a good dupetarget for this? – T.J. Crowder Dec 17 '17 at 08:14

0 Answers0