DEV Community

Helder Burato Berto
Helder Burato Berto

Posted on

πŸ”₯ Quick Tip: How to give an array of promises and only return after all either fulfilled or rejected

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' } }
    ]
  **/
});
Enter fullscreen mode Exit fullscreen mode

Note: You can use this feature with babel or another compiler enabling the ES2020 features.


Did you like it? Comment, share! ✨

Top comments (2)

Collapse
 
emtes profile image
Enmanuel de la Nuez

How does it compare to Promise.all() ?

Collapse
 
helderberto profile image
Helder Burato Berto

The difference between Promise.all and Promise.allSettled such the Promise.all when receiving a reject will stop the execution and the Promise.allSettled will execute all promises and return the status and value received independent if rejected or fulfilled.