禁止循环中使用 await
要求在 for 循环体中不使用 await
。
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));
}