【问题标题】:Avoid await in do..while() with chain dependancies [duplicate]避免在 do..while() 中等待具有链依赖关系[重复]
【发布时间】: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


【解决方案1】:

不,ESLint 规则很愚蠢。它应该是一个警告,建议也许您可以同时运行异步操作。但是不,您绝对不能,您希望您的处理是连续的。忽略该规则或完全禁用它。

【讨论】:

    猜你喜欢
    • 2014-11-09
    • 1970-01-01
    • 2014-11-09
    • 2012-01-15
    • 1970-01-01
    • 2016-03-04
    • 2012-05-11
    • 1970-01-01
    • 2022-08-03
    相关资源
    最近更新 更多