forEach 中可以使用 await 吗?
参考答案
可以用(语法不报错),但不会按预期等待:forEach 不会等待异步回调,它会同步把所有回调启动完就返回,最终函数在任何一个 await 完成前就结束了。
arr.forEach(async x => { await task(x); }); // 并行启动,无法串行
正确做法
- 串行:
for (const x of arr) { await task(x); } - 并行:
await Promise.all(arr.map(x => task(x))) - 需要限制并发:自建并发池 / p-limit。
例外:Array.prototype.forEach 不存在 for await 版本,异步迭代用 for await (const x of asyncIterable)。