Promise.all (ES2015) vs Promise.allSettled (ES2020). What's changed? π€
(Source/Credits: https://dev.to/shahzaibkhalid/promise-all-es2015-vs-promise-allsettled-es2020-what-s-changed-3k9d)
Hey! π Check out today's β‘οΈ Dev Tip π‘ π Follow me on Twitter @shahzaibkhalid for more Dev Tips! β¨...
Hey! π
Check out today's β‘οΈ Dev Tip π‘
π
Follow me on Twitter @shahzaibkhalid for more Dev Tips! β¨
Letβs say we want to run many promises to execute in parallel and wait till all of them are ready. π§
javascript
// some dummy promises to play with π
const p1 = new Promise(resolve => resolve('Shahzaib'));
const p2 = new Promise((_ ,reject) => reject('User does not exists!'));
const p3 = new Promise(resolve => resolve('Lahore'));
Promise.all (short-circuits if any of the promises is rejected)
If any of the passed promises is rejected, the promise
returned by Promise.all
immediately rejects with that error. β
javascript
Promise.all([p1, p2, p3])
.then(response => console.log(response))
.catch(error => console.log(error)); // π'User does not exists!'
Promise.allSettled (does not short-circuits)
Waits for all passed promises to settle (either resolved or rejected). π₯³
The resulting array has:
- {status: 'fulfilled', value: result}
- for successful responses
- {status: 'rejected', reason: error}
- for errors
```javascript Promise.allSettled([p1, p2, p3]) .then(response => console.log(response));
/* * π [ {status: 'fulfilled', value: 'Shahzaib'}, * {status: 'rejected', reason: 'User does not exists!'}, * {status: 'fulfilled, value: 'Lahore'} ] π / ```
Hope you learned something new today. Do let me know what do you think about this Dev Tip in the comments below. π
Peace. βοΈ
Comments section
dean
•May 1, 2024
I feel like for consistency, it should be
status: 'resolved'
rather thanstatus: 'fulfilled'
. Otherwise, that's pretty neat!The concept is great, but some renaming I think would be nice. I think the most important renaming should be
status: 'resolved'
rather than'fulfilled'
, and perhaps renamingPromise.allSettled
to something else... Not quite sure yet.shahzaibkhalid Author
•May 1, 2024
Dean, the specification uses the following naming convention:
anduser96
•May 1, 2024
Thanks for sharing!
As far as I know, you can achieve the same result with Promise.all by attaching a β.catch()β to each promise in your array.
amcsi
•May 1, 2024
I think you can only handle the first error that way, not the other errors or successes.
shahzaibkhalid Author
•May 1, 2024
Yes, we could but
Promise.allSettled
is more concise. π