admin管理员组

文章数量:1195738

I need to repeat async/await block several times, but cannot use the following code:

for (let i = 0; i <= 10; i += 1) {
   const res = await DoSomething();
 }

because it contradicts with no-await-in-loop rule.

I need to repeat async/await block several times, but cannot use the following code:

for (let i = 0; i <= 10; i += 1) {
   const res = await DoSomething();
 }

because it contradicts with no-await-in-loop rule.

Share Improve this question edited Jul 12, 2021 at 7:13 nicholaswmin 22.9k16 gold badges100 silver badges173 bronze badges asked Sep 3, 2018 at 15:44 AlexAlex 3721 gold badge5 silver badges14 bronze badges 3
  • 5 Possible duplicate of Unexpected `await` inside a loop. (no-await-in-loop) – Michael Curry Commented Sep 3, 2018 at 15:45
  • 3 Do you want to call them all at the same time or one after the other (sequentially)? – Dez Commented Sep 3, 2018 at 15:51
  • I would prefer to send them sequentially – Alex Commented Sep 3, 2018 at 16:06
Add a comment  | 

2 Answers 2

Reset to default 18

Use Promise.all if order of iteration doesn't matter

If you don't mind code running out-of-order (meaning order of each iteration doesn't matter), just use Promise.all instead:

const promises = [];

for (let i = 0; i <= 10; i += 1) {
  promises.push(DoSomething());
}
 
const responses = await Promise.all(promises);

From MDN:

The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved

Or disable the rule for that block

Otherwise if you do need to do sequential work just disable the rule for that block:

/* eslint-disable no-await-in-loop */
for (let i = 0; i <= 10; i += 1) {
  const res = await DoSomething();
}
/* eslint-enable no-await-in-loop */

BEWARE: await in a loop is, more often than not, terribly inefficient

There is a reason that the rule exists. A lot of cases where await is used in a loop are wasteful since each iteration is not dependent on the previous one, yet each iteration waits for the previous one to resolve before it even attempts to run the next one.

Promise.all is orders of magnitude more efficient in those cases since it does work in "parallel", more or less.

From ESLint no-await-in-loop docs:

Performing an operation on each element of an iterable is a common task. However, performing an await as part of each operation is an indication that the program is not taking full advantage of the parallelization benefits of async/await.

ES 9 has added a new feature for asynchronous iteration.

for await (const line of readLines(filePath)) {
   console.log(line);
}

You could try it out. Hope it works.

本文标签: javascriptFix noawaitinloop lint warningStack Overflow