Nodejs异步等待疑问

时间:2020-11-10 20:33:09

标签: node.js async-await

我有这3个功能,我不明白为什么在b完全结束之前执行c。 我需要在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 {}
}

1 个答案:

答案 0 :(得分:1)

这是因为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);
}