Hello ! 🧑🌾
Promises are available since ES2015 to simplify the handling of asynchronous operations.
Let's discover 2 Promises and their differences:
Both of them take an
iterable and return an
array containing the fulfilled Promises.
❓ So, what is the difference between them?
all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises.
As you can see, we are passing an array to Promise.all. And when all three promises get resolved, Promise.all resolves and the output is consoled.
Now, let's see if one promise is not resolved, and so, if this one is reject. What was the output ? 🛑
Promise.all is rejected if at least one of the elements are rejected. For example, we pass 2 promises that resolve and one promise that rejects immediately, then
Promise.all will reject immediately.
Since ES2020 you can use
Promise.allSettled. It returns a promise that always resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.
For each outcome object, a
status string is present :
The value (or reason) reflects what value each promise was fulfilled (or rejected) with.
Have a close look at following properties (
reason) of resulting array.
- Promise.all will reject as soon as one of the Promises in the array rejects.
- Promise.allSettled will never reject, it will resolve once all Promises in the array have either rejected or resolved.
- Google Chrome
- Microsoft Edge
- Mozilla Firefox
- Apple Safari
Cheers 🍻 🍻 🍻