有没有一种干净的方法可以无限使用异步函数?

Is there a clean way to infinitely use async functions?

根据 ESLint,像这样的一些代码不是 'clean code'

for(;;) {
  await *async function*
}

我的目标是无限循环某个函数,一个一个地执行它,而不会因为调用堆栈限制而最终导致我的应用程序崩溃。我已经考虑了一段时间,但想不出任何其他可以做同样事情的东西。 ESLint 的建议对我来说也行不通;他们建议启动循环中的所有函数,并使用 .all() 在循环外等待它们的 resolve/reject 回调。

不胜感激!我只想把这个写得尽可能干净

是的,有几种模式可用于"infinitely loop"。您可以安排在函数完成时调用相同的函数。

正如 ESLint 文档所说:

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. Or, loops may be used to retry asynchronous operations that were unsuccessful. 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.

因此,如果您认为每次迭代都需要等待,请禁用此规则。如果您可以并行化异步调用,请使用 Promise.all.

要仅在代码中的某个位置禁用 ESLint 规则,请按如下方式执行:

/* eslint-disable no-await-in-loop */
//Your code here...
/* eslint-enable no-await-in-loop */