【发布时间】:2021-09-10 09:22:17
【问题描述】:
情况如下:
我正在调用以下函数来计算大量弹性数据(bucket 变量是一组文档)
await this.computeAllData(start, range, wait, buckets, accumulator);
这是上一个函数内部的代码:
async computeAllData(start, range, wait, buckets, accumulator) {
let nextAfter = false;
do {
nextAfter = await this.computeOne(
start,
range,
wait,
buckets,
accumulator,
nextAfter
);
} while (nextAfter);
}
问题是:我不应该在循环中使用“等待”(ESLint 规则)。但是我可以找到一种方法来使用 async/await 方法来保持 do...while()(当数据被消化时停止循环)的行为。
我尝试使用 yield/generator 方法,但它失败了,对我来说太复杂了:(
请问有什么办法吗?
【问题讨论】:
-
问题不在于如何修复它,而在于为什么要实施这样的规则。您会看到规则存在,以便应用程序更好地利用并行化可能性。在开始下一个迭代之前不要等待每一个迭代。根据示例规则可能不是正确的解决方案。在您的情况下,下一次迭代需要一次迭代的结果,这使得这是一个完全有效的方法。
-
来自ESLint: Disallow await inside of loops (no-await-in-loop): When Not To Use It
[…]In many cases the iterations of a loop are not actually independent of each-other. For example, the output of one iteration might be used as the input to another. […] In such cases it makes sense to use await within a loop and it is recommended to disable the rule via a standard ESLint disable comment.
标签: javascript async-await eslint do-while