有一种干净的方法可以无限地使用异步函数吗? [英] Is there a clean way to infinitely use async functions?

查看:97
本文介绍了有一种干净的方法可以无限地使用异步函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据ESLint,这样的代码不是干净的代码"

According to ESLint some code like this is not 'clean code'

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

我的目标是无限循环某个函数,一个接一个地执行它,而不会由于调用堆栈限制最终导致我的应用程序崩溃.我已经考虑了一段时间,但无法提出其他任何可以解决此问题的建议. ESLint的建议在我的情况下也不起作用.他们建议使用.all()在循环中启动所有功能,并在循环外等待其解析/拒绝回调.

My aim is to infinitely loop a certain function, executing it one by one, without eventually crashing my app because of call stack limits. I have thought about it for some time but couldn't come up with anything else that would do the same. What ESLint suggests also wouldn't work in my case; they suggest starting all of the functions in the loop and awaiting their resolve/reject callback outside of the loop by using .all().

我们将不胜感激!我只是想尽可能简洁地写这个

Help would be appreciated! I just want to write this as cleanly as possible

推荐答案

如ESLint文档所述:

As the ESLint documentation says:

在许多情况下,循环的迭代实际上并不独立于 彼此.例如,一次迭代的输出可以用作 输入到另一个.或者,可以使用循环重试异步 操作失败.在这种情况下,使用是有道理的 在循环中等待,建议通过 标准的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.

So if it makes sense for you to wait in every iteration, disable this rule. If you can parallelize the async calls use Promise.all.

要仅在代码中的某个位置禁用ESLint规则,请执行以下操作:

To disable an ESLint rule only at some place in the code do it like this:

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

这篇关于有一种干净的方法可以无限地使用异步函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆