循环中禁止使用 await
要求 await
不在 for 循环体中使用。
Async 和 await 在 Javascript 中用于提供并行执行。如果在 for 循环中使用 await
等待每个元素,那么这将抵消使用 async/await 的好处,因为在当前元素完成之前,循环中不能处理更多元素。
一个常见的解决方案是重构代码,异步运行循环体并捕获生成的 Promise。循环结束后,您可以一次性等待所有 Promise。
无效
async function doSomething(items) {
const results = [];
for (const item of items) {
// Each item in the array blocks on the previous one finishing
results.push(await someAsyncProcessing(item));
}
return processResults(results);
}
有效
async function doSomething(items) {
const results = [];
for (const item of items) {
// Kick off all item processing asynchronously...
results.push(someAsyncProcessing(item));
}
// ...and then await their completion after the loop
return processResults(await Promise.all(results));
}