首页 > 解决方案 > 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 {}
}

标签: node.jsasync-await

解决方案


这是因为forEach不等待任何已执行的处理程序。您可以使用Promise.allfor of

await Promise.all(Object.keys(targets).map(key => d(key)))
for (const key of Object.keys(targets)) {
  await d(key);
  console.log(globalVariable);
}

推荐阅读