[英]Fix no-await-in-loop lint warning
I need to repeat async/await block several times, but cannot use the following code:我需要多次重复 async/await 块,但不能使用以下代码:
for (let i = 0; i <= 10; i += 1) {
const res = await DoSomething();
}
because it contradicts with no-await-in-loop rule.因为它与 no-await-in-loop 规则相矛盾。
Promise.all
if order of iteration doesn't matter如果迭代顺序无关紧要,请使用Promise.all
If you don't mind code running out-of-order (meaning order of each iteration doesn't matter), just use Promise.all
instead:如果您不介意代码乱序运行(意味着每次迭代的顺序无关紧要),只需使用Promise.all
:
const promises = [];
for (let i = 0; i <= 10; i += 1) {
promises.push(DoSomething());
}
const responses = await Promise.all(promises);
The Promise.all(iterable) method returns a single Promise that resolves when all of the promises in the iterable argument have resolved Promise.all(iterable) 方法返回一个 Promise,当 iterable 参数中的所有承诺都已解决时,该 Promise 会解决
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循环中的await
通常是非常低效的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.在循环中使用await
很多情况都是浪费的,因为每次迭代都不依赖于前一次,但每次迭代甚至在尝试运行下一次之前都会等待前一次解决。
Promise.all
is more efficient in those cases since it does work in "parallel", more or less. Promise.all
在这些情况下效率更高,因为它或多或少地以“并行”方式工作。
From ESLint no-await-in-loop docs :来自ESLint no-await-in-loop 文档:
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.但是,在每个操作中执行 await 表明程序没有充分利用 async/await 的并行化优势。
ES 9 has added a new feature for asynchronous iteration. ES 9 为异步迭代添加了一个新功能。
for await (const line of readLines(filePath)) {
console.log(line);
}
You could try it out.你可以试试看。 Hope it works.希望它有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.