Everything about javascript Promise.all()

Pravin Lolage
Pravin Lolage
Published in
3 min readAug 10, 2018

As we have heard about synchronous and asynchronous coding patterns. Javascript behaves asynchronously meaning that it does not wait for the specific line of code and will immediately execute the next one without halting the execution. This behavior confuses lots of developers who have worked on the synchronous code.

What is asynchronous?

Let’s imagine you are at the Cafe. You will order your food and the waiter will serve you the same. But that does not mean a waiter will not take other people orders. In short, the waiter will take orders from multiple customers and forward this to the chef in the kitchen. Now the chef will prepare the food according to the orders and whichever is completed he will ask the waiter to serve the food to that customer.

Similarly, if we consider the Server as a chef, Javascript as a waiter and customer as requests. So we will get to know that javascript serves a response to the requests asynchronously. This is what all about the asynchronous mechanism in Javascript.

Promise.all()

Now assume, we have the following function:

let multiplyNumber = (value) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(value * 10), 2000);
});
}

multiplyNumber is a function which multiplies the given parameter by 10 and takes 2 seconds to execute intentionally.

Now it’s time to get the result by passing our set of input parameters. In a general way, we use the below technique:

multiplyNumber(10).then((result) => {
console.log("Multiply of 10 is", result); // prints => Multiply of 10 is 100
});
multiplyNumber(20).then((result) => {
console.log("Multiply of 20 is", result); // prints => Multiply of 20 is 200
});

Now if we have 10 such inputs, it’s not a standard way to call multiplyNumber 10 times. To resolve this we use the Promise.all() to get the desired result. Let’s see:

let promises = [];
let inputParams = [10, 20];
for(let i=0; i<inputParams.length; i++) {
promises.push(multiplyNumber(inputParams[i]));
}
Promise.all(promises).then(resultArray => {
console.log("Combined result is", resultArray); // prints => Combined result is [100, 200]
});

This will resolve, redundant code of calling the same function for each input separately.

Error handling in Promise.all()

Now, suppose one of the calls fails what will happen? Let’s see:

let multiplyNumber = (value) => {
return new Promise((resolve, reject) => {
if(value == 20) {
setTimeout(() => reject("20 is not allowed"), 2000);
} else {
setTimeout(() => resolve(value * 10), 2000);
}
});
}

We modified the multiplyNumber function, it will reject the promise with an error if we received 20 as input.

let promises = [];
let inputParams = [10, 20];
for(let i=0; i<inputParams.length; i++) {
promises.push(multiplyNumber(inputParams[i]));
}
Promise.all(promises).then(resultArray => {
console.log("Combined result is", resultArray); // this wont be called.
}).catch(err => {
console.log("Error is", err); // prints => Error is 20 is not allowed
});

As soon as the error is caught in the catch block, it will halt everything, an error will be printed.

Summary

So in the above example, I have used the same function called in parallel, you can use the different functions in parallel. Promise.all() is useful in the cases where you want to perform some actions in parallel and if one of action fails then revert everything in the catch block. e.g. If you are running some transactions over the database in parallel and if one of the query fails then you can rollback everything.

Thanks for reading!

If you like the above article please clap the same and if you don’t like please put your thoughts in comments so that I can improve it.

You can reach me out on Linkedin, Quora.

--

--

Pravin Lolage
Pravin Lolage

A software enthusiast with almost 8+ years of experience in programming trying to share my knowledge.