版本

no-await-in-loop

不允許在迴圈內使用 await

對可迭代物件的每個元素執行操作是一項常見的任務。然而,在每個操作中執行 await 表示程式沒有充分利用 async/await 的並行化優勢。

通常,程式碼應重構為一次建立所有 Promise,然後使用 Promise.all() 取得結果。否則,每個後續操作都將在先前的操作完成後才會開始。

具體而言,以下函式應如所示重構

async function foo(things) {
  const results = [];
  for (const thing of things) {
    // Bad: each loop iteration is delayed until the entire asynchronous operation completes
    results.push(await bar(thing));
  }
  return baz(results);
}
async function foo(things) {
  const results = [];
  for (const thing of things) {
    // Good: all asynchronous operations are immediately started.
    results.push(bar(thing));
  }
  // Now that all the asynchronous operations are running, here we wait until they all complete.
  return baz(await Promise.all(results));
}

規則詳情

此規則不允許在迴圈主體內使用 await

範例

此規則的正確程式碼範例

在遊樂場中開啟
/*eslint no-await-in-loop: "error"*/

async function foo(things) {
  const results = [];
  for (const thing of things) {
    // Good: all asynchronous operations are immediately started.
    results.push(bar(thing));
  }
  // Now that all the asynchronous operations are running, here we wait until they all complete.
  return baz(await Promise.all(results));
}

此規則的不正確程式碼範例

在遊樂場中開啟
/*eslint no-await-in-loop: "error"*/

async function foo(things) {
  const results = [];
  for (const thing of things) {
    // Bad: each loop iteration is delayed until the entire asynchronous operation completes
    results.push(await bar(thing));
  }
  return baz(results);
}

何時不使用它

在許多情況下,迴圈的迭代實際上並非彼此獨立。例如,一個迭代的輸出可能被用作另一個迭代的輸入。或者,迴圈可以用於重試未成功的非同步操作。或者,迴圈可以用於防止您的程式碼並行發送過多的請求。在這種情況下,在迴圈內使用 await 是有意義的,建議透過標準的 ESLint 停用註解來停用該規則。

版本

此規則在 ESLint v3.12.0 中引入。

資源

變更語言