Is there a clean way to infinitely use async funct

2019-07-28 10:33发布

问题:

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.