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

示例

L9CfmI+BHDwYx59RS77HEHanEO40ClscOusGIf+RQNhowUc7Zz7f+Hb0VCfK93W9

/*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));
}

P6820Z8G9wSG50SW7a53cABVQLzOImcIRV+hQUkxjXCO67pG2wyQwHch0OYzHhMo

/*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);
}

何时不使用

6weNeLrlXW5uxwmZWEK9n/iOxXhn5Up29tqCT4DlyNVUKPCrVk2O5Ot6bJ0O7xFjjc7ZQepKwiUV4FGYkSkOjhQ9I++/Nz2nBia0A0RX7Bma36VmZgfZNRIUFxeU4nRGWdM1f2GPnxUlFWITrwpRDMlbt3EwfMuIFErWI4d6bbilvNvQ2QDgfzoPKx6nL5v3CRBGaH6po6HKXp14Id1P5epo/ZFqB7yFS5I3iY3D0ParAJ4NVfFefob0xkaIs8gxlHA5fJQ/I5NhQ0VpV1SOlmgqkhvnhK3kCgiPz8Xpt0PKh42topKpB0JFoMnAbZNvZSpnuPMs3eW2hOWpSKHO5Nwsz+4Kbeo7szlvpn1GV1GdFVQxd3CIwfngPOILwiYXyZJyqMw/Ix47zr+UPiwCdctaJMfaIQBfk1qunKoif0HZmvbkDSeObLmr2Krks2PMu0cDSN3SkywPBVJTK/ZB8SkU6auMU/CIPv3Cjpy2fr5YsIBeZxM4W6/7+MXTPT2OJQ+BtVPYtKzZbKiqBWEjY0MlO5IqZJrLA7gfqNu0Gfs=