DEV Community

Mitesh Kamat
Mitesh Kamat

Posted on

I promise...I'll catch all

Introduction

This article is about error handling in case of Promise.all

What does Promise.all() do??

The Promise.all() method returns a single Promise that fulfills when all of the promises passed as an iterable have been fulfilled.

For example,

const firstPromise = Promise.resolve(3);
const secondPromise = 10;
const thirdPromise = new Promise(function(resolve, reject) {
  setTimeout(resolve, 1000, 'third promise');
});

Promise.all([firstPromise , secondPromise , thirdPromise ]).then(function(values) {
  console.log(values);
});
// output: Array [3, 10, "third promise"]

Now, there is something called fail-fast behavior.

Promise.all is rejected if any of the elements within the iterable are rejected. For example, if you pass in two promises of which one resolves after a timeout and one promise rejects immediately, then Promise.all will reject immediately.
Have a look:

const p1 = new Promise((resolve, reject) => { 
  setTimeout(() => resolve('one'), 1000); 
});
const p2 = new Promise((resolve, reject) => {
  reject(new Error('rejecting....'));
});

Promise.all([p1, p2])
.then(values => { 
  console.log(values);
})
.catch(error => { 
  console.error(error.message)
});

//console: 
//"rejecting...."

In the above code, P1 will resolve and return a response after timeout but since P2 throws an error Promise.all() will reject and exit with an error message.

But, in real life scenarios you don't want the execution to stop just because one promise failure.

If we have to change this, we need to handle each promise to get desired results.

const first = new Promise((resolve, reject) => { 
  setTimeout(() => resolve('delayed response'), 1000); 
}); 

const second= new Promise((resolve, reject) => {
  reject(new Error('rejection'));
});

Promise.all([
  first.catch(error => { return error }),
  second.catch(error => { return error }),
]).then(values => { 
  console.log(values[0]) // "delayed response"
  console.error(values[1]) // "Error: rejection"
})

Notice the difference in console statements. This time we get response from both the promises even if one promise throws error.

This is because, we are handling each promise within the iterable.

That's how we promise to catch all. Hope this was helpful.
Cheers !!!

Top comments (0)