Promise all method

Mateusz -

Promise.all() allows us to combine all our promises into one. Let’s assume a situation where we need to make 3 requests at the same time and they are dependent on each other. And we want to run some code only if these 3 promises are resolved.

//
const promise1 = () => Promise.resolve('Promise 1 data, list of carrots');
const promise2 = () => Promise.resolve('Promise 2 data, list of onions');
const promise3 = () => Promise.resolve('Promise 3 data, list of apples');
//

Normally, we would probably call these promises and use 3 times then() syntax, as below. So we have three separate functions and they are running at three different times and for example we have no idea which one will be resolved first.

//
promise1().then()
promise2().then()
promise3().then()
//

To meet our needs we can use Promise.all(). As an argument this method takes an array of promises.

//
Promise.all([promise1(), promise2(), promise3()]).then((allResults) => {
    console.log(allResults[2]); //Promise 3 data, list of apples
    console.log(allResults[1]); //Promise 2 data, list of onions
    console.log(allResults[0]); //Promise 1 data, list of carrots
});
//

Now we have all our promises combined into one and we have a good access to control each of them. When all promises get resolved our response will be an array of responses from each promise.

Rejected situation

In Promise.all() method we will only get the results of our promises when all promises were resolved. What happens if any of them get rejected?

//
const promise1 = () => Promise.resolve('Promise 1 data, list of carrots')
const promise2Rejected = () => Promise.reject('Promise 2 data, list of onions')
const promise3 = () => Promise.resolve('Promise 3 data, list of apples')
//

Promise.all([promise1(), promise2(), promise3()]).then((allResults) => {
    console.log(allResults[2]);
    console.log(allResults[1]);
    console.log(allResults[0]);
}).catch((error) => {
    console.log(`Error in: ${error}`); //Promise 2 data, list of onions
});
//

We need to handle this scenario by using catch() method. Since only one rejected case is needed for Promise.all() to fail, we won’t see any console logs listing carrots or apples. We will only see console log inside our catch() method.