DEV Community

Discussion on: Don't await in loops

Collapse
 
pentacular profile image
pentacular

However, this is far from optimal, the whole point of asynchronous operations is that they can be done in parallel.

async operations in javascript cannot be done in parallel -- they can only be interleaved.

The purpose of async is to allow another operation to occur when one is blocked.

For this reason, there is absolutely nothing wrong with using async in loops -- it is perfectly reasonable to have async operations with a required ordering.

Of course, it's nice to avoid unnecessary ordering constraints on operations -- and this can give you more alternative things to do when one is blocked.

Collapse
 
arnaud profile image
Arnaud

Thank you for your comment. You are correct, sometimes async operations need to be done in a given order. The point I am looking to make in the article is to use catch blocks when the behavior of Promise.all rejecting immediately upon any of the input promises rejecting is not desired.

Collapse
 
pentacular profile image
pentacular

I think you're still making incorrect claims about parallelism.

Now the entire loop will be as slow as its slowest operation, in our case this is ~1 second, 5.5x faster!

No, the entire loop will be at least as slow as the sum of all of its operations.

It's just that in this particularly contrived example, the operations don't do any work -- they just sit around doing nothing for a while -- so this is all dead-time.

The dead-time can be 'parallelized' because no work occurs, but the over-all story you're making in the article seems very misleading to me.

Thread Thread
 
arnaud profile image
Arnaud • Edited

The 'contrived example' is to illustrate the purpose of this lint rule: eslint.org/docs/rules/no-await-in-...

Some people disable this rule, not because they need to run operations in order, but because they don't know how to disable the fail fast behavior of Promise.all as explained at the end of this page: developer.mozilla.org/en-US/docs/W... under "Promise.all fail-fast behaviour".

Apparently I am not doing a good job at explaining it, thanks for the feedback, I've made some tweaks based on your observations.