How to loop async/await?

╄→尐↘猪︶ㄣ 提交于 2020-12-29 07:40:45

问题


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.


回答1:


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 */

await in a loop is most often than not, very 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 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.




回答2:


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.



来源:https://stackoverflow.com/questions/52152842/how-to-loop-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!