Member-only story
Promise.all is overrated! And await in for loop is underrated!
Promise.all
is bascially used for resolving all the promises created in parallel to speed up the execution time instead of resolving one promise at a time. But here’s the catch. If these all are very high in number and these promises contain database or elasticsearch queries, it will blow up because resources will be overloaded at a specific amount of time and it will generally throw an error. Also, in case if one promsie execution is dependent on the previous part, still you can’t use promise.all because you might need to fetch data for previous promise execution which can be used in next promise data. For example in some APIs, next set of results will require the token from the previous set of results.
Using await in for loops allow first promise to be awaited and the next promises resolves. It might be slow but is reliable.
It highly depends on your usecase whether you want to use Promise.all
or await
single Promise at a time. Only use Promise.all
if it satisfies two conditions:
- The promises are not dependent of each other.
- Executing in parallel wont’ give you database/resource overload.
You can also execute promises in chunks provided there is no dependency between promises. For example, if we have 100 promises and you want to execute in such a way that the database won’t get overloaded and time taken won’t be too much, you can use `Promise.all` in set of 10 in an array and next 10. So it will take 10 synchronous loops in order to execute all the parallel promises. I had this strategy while I had issue with database overloads.