node.js - Nodejs async-await 疑惑
问题描述
我有这 3 个函数,但我不明白为什么 c 在 b 完全结束之前执行。我需要在 c 中使用一个全局变量,该变量由我在 b 中调用的函数 d 填充。
var globalVariable = {};
async function start() {
await b();
await c();
}
async function b()
var targets = {} //it is a populated array of objects
Object.keys(targets).forEach(async(key) => {
await d(key);
console.log(globalVariable); //it prints the correct value but after the function c is executed
})
}
async function d(key){
globalVariable.key = await getValueFromDb(); //returns value 5
}
async function c(){
await doStuffOnDb(); //not revelant stuff on db
console.log(globalVariable); //it prints {}
}
解决方案
这是因为forEach
不等待任何已执行的处理程序。您可以使用Promise.all
或for of
。
await Promise.all(Object.keys(targets).map(key => d(key)))
for (const key of Object.keys(targets)) {
await d(key);
console.log(globalVariable);
}
推荐阅读
- javascript - React Router - 链接点击时的 URL 更新但组件未呈现
- javascript - 在 Javascript 日期选择器上阻止特定日期
- ios - UIButton 上的 contextMenuInteraction
- python - 使用 xlsxwriter 在 dict 中迭代的问题
- linq - Entity Framework Core 中的日期操作
- c++ - Arduino:如何在不知道伺服需要移动到的确切位置的情况下移动伺服
- templates - 是否可以在 SharePoint 网站模板中包含 Flow/Power Automate?
- html - 在 GITHUB PAGES 上创建网站时出错
- azure - 使用 Postman 的 Azure 集线器通知 rest api 时未收到通知
- python - 一些 CSV 单元格包含在“引号”中,而另一些则没有