使用 forEach 获取异步匿名函数的所有结果

Sam*_*ack 0 javascript node.js async-await typescript ecmascript-6

async function multiply(task) {
  return task * 2
}

var arr = [1, 2, 3, 4];

var res = [];
arr.forEach(async task => {
  res.push(await multiply(task))
});

console.log(res)
Run Code Online (Sandbox Code Playgroud)

输出

[] 
Run Code Online (Sandbox Code Playgroud)

预期的

[2,4,6,8]
Run Code Online (Sandbox Code Playgroud)

我想等到所有项目都乘以 2,然后将结果作为数组得到。

注意: multiply是一个异步函数,因此必须async task 在 forEach 内部写入。我不能改变乘法。

Fel*_*ing 7

不要使用forEach. 使用.map创建的承诺和使用数组Promise.all来解决所有的人:

const result = await Promise.all(arr.map(multiply));
Run Code Online (Sandbox Code Playgroud)

forEach 不知道异步函数,因此您不能让它“等待”其回调函数中发生的异步内容。