The right way to use loops in Promises

According to this link (Rookie # 2 bug) I should not use loops inside Promises, but instead Promise.all(iterable) .

Does this apply to all cycles? Promise.all(iterable) takes an array of size n. If I used Promise.all(iterable) , then I would get an array of size n as a result (i.e., Iterable_A).

What if I want to repeat the iteration and only want to add some elements that satisfy my condition to another iterable (for example, iterable_B) and want to return iterable_B instead of iterable_A? Should I use Promise.all() too?

+3
javascript promise asynchronous callback
source share
1 answer

I should not use loops inside Promises

No, rather the opposite: you should not use promises inside loops.

Of course, this is also common. Sometimes you just need a loop structure. What you should not do is forget to collect the promises that are created in the body of the loop in some iterable, which you can pass to Promise.all to wait for all asynchronous things running in this loop.

map method , as suggested in the article, of course, you should just return to give a promise from the callback (as always). Using for / while / .forEach makes it a bit more complicated as you have to manually push promises in some kind of array (which is not only ugly, but also wrong).

However, if you are not dealing with asynchronous tasks inside your loop, you can do whatever you want. For example, both

 Promise.all(values.filter(syncPredicate).map(asyncFn)) 

and

 Promise.all(promises).then((values) => values.filter(syncPredicate)) 

totally beautiful. This gets a little trickier when you have the asynchronous filter predicate, I would recommend looking for a promise utility library in this case.

You will also need to understand that asynchronous tasks launched from the synchronous loop construct will run in parallel. If you intend to run them sequentially (expect each iteration), you should try to formulate a loop using a recursive structure .

+4
source share

All Articles