On this simple trick, I'll show you how to give an array of promises and only return after all either fulfilled or rejected.
const promises = [
Promise.resolve({ name: 'Mikkel' }),
Promise.resolve({ name: 'Jonas' }),
Promise.resolve({ name: 'Adam' })
];
Promise.allSettled(promises).then(results => {
console.log('All Promises Settled', results);
/**
'All Promises Settled' [
{ status: 'fulfilled', value: { name: 'Mikkel' } },
{ status: 'fulfilled', value: { name: 'Jonas' } },
{ status: 'fulfilled', value: { name: 'Adam' } }
]
**/
});
Note: You can use this feature with babel or another compiler enabling the ES2020 features.
Did you like it? Comment, share! ✨
Top comments (2)
How does it compare to Promise.all() ?
The difference between
Promise.all
andPromise.allSettled
such thePromise.all
when receiving a reject will stop the execution and thePromise.allSettled
will execute all promises and return the status and value received independent if rejected or fulfilled.