为什么函数在第一个函数被调用之前被调用

时间:2017-12-16 20:32:14

标签: javascript node.js asynchronous mongoose async-await

我正在制作一个节点js应用程序,我有问题,虽然我使用await + async它不会做的事情。我需要调用第一个函数然后调用第二个函数,但第二个函数总是在第一个函数调用之前这里是代码

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);
            }
        });
    }

0 个答案:

没有答案