首页 > 解决方案 > 在 Node.js 中完成另一个异步函数之前发生的异步函数

问题描述

现在,老实说,我真的不知道 node.js 中的 async/await,但我被卡住了 :(

这是我的代码

async function main(){
    var pokemonID = getRandomPokemon();

    getJSON(pokemonID)
        .then(data => {getPokemonInfo(data)})
        const tempData = require('./temp_data.json');
        await down.load(tempData.pokemonImg)
        var tweetText = "Today's Pokemon of the day is " + tempData.pokemonName + ", which is a " + tempData.pokemonType + " type pokemon"
        await tweet.tweeter(tweetText)

}

main()

我没有收到错误,但第二个异步函数在第一个异步函数之前执行。

标签: javascriptnode.jsasynchronousasync-await

解决方案


await还可以添加getJSON

async function main(){
    var pokemonID = getRandomPokemon();

    await getJSON(pokemonID)                     //set await 
        .then(data => {getPokemonInfo(data)})
        const tempData = require('./temp_data.json');
        await down.load(tempData.pokemonImg)
        var tweetText = "Today's Pokemon of the day is " + tempData.pokemonName + ", which is a " + tempData.pokemonType + " type pokemon"
        await tweet.tweeter(tweetText)

}


推荐阅读