首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

no-await-in-loop

对迭代器的每个元素执行操作是一项常见任务。然而,执行await每个操作的一部分是一个表示该程序未服用的并行化的好处充分利用async/await

通常,应该重构代码以一次创建所有的承诺,然后使用访问结果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在循环体内使用。

示例

此规则的正确代码示例:

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

此规则的错误代码示例:

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 3.12.0中引入。

资源

扫码关注腾讯云开发者

领取腾讯云代金券