There are tons of articles online that offer tutorials about how to use Promise.all. I will not reiterate those. In this article, I aim to brief summarise the use of Promise.all in real-world projects for those programmers transitioning from junior to mid-level.
What do we need to keep in mind when considering using Promise.all
- Order matters. Promise.all returns the results in the same order as the source.
- Fail one, Fail all. If one of the promise rejects, then the Promise.all will not wait for the remaining promise to execute but rejects right away.
When do we need Promise.all
In real project, normally when we have an array of data, for each element in the array, we need to do some async/await operations, this is where we need Promise.all. For example, in the following code snippets from a real project, we have an array called idsForDelete
, for each id in this array, we need to call an async method removeMonitorTask(apiKey, id)
. Therefore, we use Promise.all to do async/await calls on all ids in the array.
1 | ... |
How do we handle exceptions with Promise.all
There are two ways of handling exceptions with Promise.all:
- catch an exception at the end of Promise.all;
- catch an exception in each individual promise.
Only catching exceptions in the latter way when we need to:
- Keep the results of other promise
- Want to know the reason for each rejected promise
Check the following example:
1 | p1 = Promise.resolve(10); |
Execution result:
1 | -- internal err: test |
As we can see from the execution result that even p3 is rejected, we still get the results of previous p1 and the p2 afterwards.
What if we only catch the exception after Promise.all?
1 | p1 = Promise.resolve(10); |
Result:
1 | -- err: test |
As shown above, Promise.all rejects all, we are not able to see the result of p2.
That is it, that is all you need to know about Promise.all in most of the time when developing real-world projects.