Advance JavaScript

JavaScript – Promise.all


As we know that a promise is used to check any condition. And promise either ends up with either resolve or reject. If promise is resolved then we use then() function. If promise is rejected then we use catch() function to throw errors.

In JavaScript, there might be multiple promises. If we write code for each promise() function, the code will be very lengthy. In order to resolve this problem, in JavaScript ES6 version a new function introduced called promise.all().

In the above diagram, it is very clear that if all the promises are resolved then only it will move to then() state, otherwise move to catch() state.

Let us understand with the syntax given below.

let prom1 = new Promise(function(resolve, reject){
    console.log('First Promise Program');
    resolve('First');
});

let prom2 = new Promise(function(resolve, reject){
    console.log('Second Promise Program');
    resolve('Second');
});

Promise.all([prom1, prom2]).then().cath();

In the above syntax, you can see there two different promises. But using promise.all(), you can have to write only a then() function and a single catch() function. It means if prom1 and prom2 both will be resolve then only the then() method will be called other catch() method will show error.

Please see an example for Promise.all()

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Promise All</title>

    <script>
        let prom1 = new Promise(function(resolve, reject){
            setTimeout(() => {
                console.log('The First promise has resolved.');
                resolve(10);
            }, 1*1000);
        });

        let prom2 = new Promise(function(resolve, reject){
            setTimeout(() => {
                console.log('The Second promise has resolved.');
                resolve(20);
            }, 2*1000);
        });

        let prom3 = new Promise(function(resolve, reject){
            setTimeout(() => {
                console.log('The Third promise has resolved.');
                resolve(30);
            }, 3*1000);
        });

        Promise.all([prom1, prom2, prom3]).then((result)=>{
            console.log(`Results: ${result}`);
        }).catch((error) => {
            console.log(`Errors: ${error}`);
        });
    </script>
</head>
<body>

</body>
</html>

If we execute this program in browser and do inspect element, we get the result as given below:


A program to find out the sum of all return value by each promise.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Promise All</title>

    <script>
        let prom1 = new Promise(function(resolve, reject){
            setTimeout(() => {
                console.log('The First promise has resolved.');
                resolve(10);
            }, 1*1000);
        });

        let prom2 = new Promise(function(resolve, reject){
            setTimeout(() => {
                console.log('The Second promise has resolved.');
                resolve(20);
            }, 2*1000);
        });

        let prom3 = new Promise(function(resolve, reject){
            setTimeout(() => {
                console.log('The Third promise has resolved.');
                resolve(30);
            }, 3*1000);
        });

        var total = 0;
        Promise.all([prom1, prom2, prom3]).then((result)=>{
            for(i in result){
                total += result[i];
            }
            console.log(`Results: ${result}`);
            console.log(`Total: ${total}`);
        }).catch((error) => {
            console.log(`Errors: ${error}`);
        });
    </script>
</head>
<body>

</body>
</html>


#CONSOLE
The First promise has resolved.
The Second promise has resolved.
The Third promise has resolved.
Results: 10,20,30
Total: 60

If a promise failed to process:-

Now You should also what would happen, if any promise reject. Suppose promise failed to process. Then let us see the result.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Promise All</title>

    <script>
        let prom1 = new Promise(function(resolve, reject){
            setTimeout(() => {
                console.log('The First promise has resolved.');
                resolve(10);
            }, 1*1000);
        });

        let prom2 = new Promise(function(resolve, reject){
            setTimeout(() => {
                console.log('The Second promise failed.');
                reject("Failed.");
            }, 2*1000);
        });

        let prom3 = new Promise(function(resolve, reject){
            setTimeout(() => {
                console.log('The Third promise has resolved.');
                resolve(30);
            }, 3*1000);
        });

        var total = 0;
        Promise.all([prom1, prom2, prom3]).then((result)=>{
            for(i in result){
                total += result[i];
            }
            console.log(`Results: ${result}`);
            console.log(`Total: ${total}`);
        }).catch((error) => {
            console.log(`Errors: ${error}`);
        });
    </script>
</head>
<body>

</body>
</html>

#CONSOLE
The First promise has resolved.
The Second promise failed.
Errors: Failed.
The Third promise has resolved.

We can now optimize the above example by creating a reusable function for promise().

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Promise All</title>
    <script>
        let promiseCall = function(returnValue, message){
            return function (resolve, reject){
                setTimeout(() => {
                    console.log(`The ${message} has been resolved.`);
                    resolve(returnValue);
                }, returnValue*100);
            }
        };

        let prom1 = new Promise(promiseCall(10, 'First'));
        let prom2 = new Promise(promiseCall(20, 'Second'));
        let prom3 = new Promise(promiseCall(30, 'Third'));

        var total = 0;
        Promise.all([prom1, prom2, prom3]).then((result) => {
            for(var i in result){
                total += result[i];
            }
            console.log(`Results: ${result}`);
            console.log(`Total: ${total}`);
        }).catch((error) => {
            console.log(`Errors: ${error}`);
        });
    </script>
</head>
<body></body>
</html>

#CONSOLE
The First has been resolved.
The Second has been resolved.
The Third has been resolved.
Results: 10,20,30
Total: 60