【发布时间】:2019-11-10 04:17:28
【问题描述】:
我正在编写代码以从 api 获取数据并将其保存在 mongodb 数据库中。我写的代码是:
getSquadList: async (ctx) => {
var query = ctx.request.query;
var squadList = await getSquadsOfMatch(query.matchId);
if (squadList.length <= 1) {
var response = await axios.get(
`${strapi.config.currentEnvironment.getSquadListApi}?apikey=${strapi.config.currentEnvironment.cricApiKey}&unique_id=${query.matchId}`
);
squadList = response.data.squad;
var match = await Match.findOne({
unique_id: query.matchId
});
var team1Squad, team2Squad;
await squadList.forEach(async squad => {
if (squad.name === match['team-1']) {
team1Squad = {
name: match['team-1'],
match_id: match['unique_id'],
match: match['_id'],
};
await new Squad(team1Squad).save();
console.log('1');
} else if (squad.name === match['team-2']) {
team2Squad = {
name: match['team-2'],
match_id: match['unique_id'],
match: match['_id'],
};
await new Squad(team2Squad).save();
console.log('2');
}
});
squadList = await getSquadsOfMatch(query.matchId);
console.log('3');
}
ctx.send(squadList);
}
我使用了 console.log() 来查看执行顺序。我想要的顺序是 1 2 3 但实际输出是 3 1 2 我怎样才能让程序在最后执行这些行。 小队列表 = 等待 getSquadsOfMatch(query.matchId); console.log('3');
【问题讨论】:
-
你不能
await和.forEach,因为.forEach调用本身不是异步的。 -
你可以在 medium 上查看this article
标签: javascript node.js mongoose async-await