在Node.js中发生在另一个异步函数之前的异步函数



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

这是我的代码

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()

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

您可以将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)
}

async function main(){
var pokemonID = getRandomPokemon();
try {    
const data = await getJSON(pokemonID);
const pakemonData =  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)
} catch (e) {
console.log(e)}
}

简短的回答:而不是使用:

getJSON(pokemonID)
.then(data => {getPokemonInfo(data)})

应该使用:

const data = await getJSON(pokemonId);
// if getPokemonInfo() is asynchronous, use await, if not remove it
await getPokemonInfo(data);

既然你在异步函数中,如果你想让其他异步函数顺序执行,你可以等待它们。


async function main(){
var pokemonID = getRandomPokemon(); // if this is asynchronous then modify this to await getRandomPokemon();
var data = await getJSON(pokemonID);
var info = await getPokemonInfo(data); // assuming this is async as well, if not then remove the await

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

最新更新