Is there a clean way to infinitely use async functions?

我怕爱的太早我们不能终老 提交于 2019-12-11 08:03:42

问题


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

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

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


回答1:


As the ESLint documentation says:

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.

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.

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 */



回答2:


Yes, there are several patterns which could be used to "infinitely loop". You can schedule the same function to be called when the function completes.



来源:https://stackoverflow.com/questions/48370317/is-there-a-clean-way-to-infinitely-use-async-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!