JavaScript Promise.race() vs. Promise.all()

JavaScript Promise.race() vs Promise.all()

In this article, I am going to discuss JavaScript Promise.race() vs Promise.all() with Examples. Please read our previous article where we discussed JavaScript Promise Chaining in detail. 

JavaScript Promise.all()

The JavaScript Promise.all() static method is used to execute multiple promises in parallel. This method is used to compute the result of multiple asynchronous operations. It is typically used when there are multiple asynchronous tasks that are dependent on one another to complete successfully, as it does not wait and will reject immediately upon any of the input promises rejecting.

The Promise.all() static method accepts a list or iterable of Promises(e.g.: Array) and returns a new Promise that resolves when all Promise in the iterable has resolved or rejects if at least one of the promises in the iterable has rejected. When an empty iterable is passed, then this method returns (synchronously) an already resolved promise

Syntax: Promise.all(iterable);

The Promise.all() method accepts a list of promises/array of promises as an argument. Let’s walkthrough the example to understand the promise.all() method in deeply

Resolved Promises example

Example1:

<html>
<head>
    <title>JavaScript Promise.all() resolved promises example1</title>
</head>
<body>
    <script>
        const promise1 = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(3);
            }, 3000);
        });
        const promise2 = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(2);
            }, 2000);
        });

        Promise.all([promise1, promise2]).then((res) => {
            console.log(res[0]);
            console.log(res[1]);
        });
    </script>
</body>
</html>

Output: 3 2

Example2:
<html>
<head>
    <title>JavaScript Promise.all() resolved promises example2</title>
</head>
<body>
    <script>
        // wait "millis" ms, then resolve with "value"
        function resolve(value, milliseconds) {
            return new Promise((resolve, reject) => {
                setTimeout(() =>
                    resolve(value), milliseconds)
            });
        }
        // wait "millis" ms, then reject with "reason"
        function reject(reason, milliseconds) {
            return new Promise((resolve, reject) => {
                setTimeout(() =>
                    reject(reason), milliseconds)
            });
        }

        Promise.all([resolve(100, 5000), resolve(200, 6000), resolve(300, 7000)])
            .then(values => console.log(values)); // outputs "[100, 200, 300]" after 7 seconds.
    </script>
</body>
</html>

Output:

JavaScript Promise.race() vs Promise.all() with Examples

In the above 2nd example we created 3 promises to resolve the 100, 200, and 300 value after 5,6 and 7 seconds using the setTimeout() method. We set the setTimeout() function to simulate the asynchronous operations.

In order to make all three promises run parallel and to wait for all three promises to resolve, we have to use the promise.all() method. When all the three promises resolved then the values from these promises are passed into the callback of then() method as an array and displayed the array values using console.log().

Rejected Promises example

Example1:

<html>
<head>
    <title>JavaScript Promise.all() rejected promises example1</title>
</head>
<body>
    <script>
        const promise1 = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(3);
            }, 3000);
        });
        const promise2 = new Promise((resolve, reject) => {
            setTimeout(() => {
                reject(2);
            }, 2000);
        });

        Promise.all([promise1, promise2]).then((res) => {
            console.log(res[0]);
            console.log(res[1]);
        });
    </script>
</body>
</html>

Output:

JavaScript Promise.race() vs Promise.all() with Examples

Example2:
<html>
<head>
    <title>JavaScript Promise.all() rejected promises example2</title>
</head>
<body>
    <script>
        // wait "millis" ms, then resolve with "value"
        function resolve(value, milliseconds) {
            return new Promise((resolve, reject) => {
                setTimeout(() =>
                    resolve(value), milliseconds)
            });
        }
        // wait "millis" ms, then reject with "reason"
        function reject(reason, milliseconds) {
            return new Promise((resolve, reject) => {
                setTimeout(() =>
                    reject(reason), milliseconds)
            });
        }

        Promise.all([resolve(100, 5000), reject('Error!', 6000), resolve(200, 7000)])
            .then(values => console.log(values)) // it will not execute
            .catch(error => console.log(error))//outputs "Error!" after 6 seconds.
    </script>
</body>
</html>

Output: Error!

In the above 2nd example, we created 3 promises, the first promise is resolved the 100 after 5 seconds, the second promise is rejected with an error message after 6 seconds and the third promise resolve the 200 after 7 seconds.

As a final result, the return promise is rejected due to the second promise is rejected. Hence, the catch() method is executed to display the reason with the error message for the rejected promise.

JavaScript Promise.race()

The JavaScript Promise.race() static method accepts an iterable of Promises and returns a new Promise which resolves or rejects as soon as the first of the promises in the iterable has resolved or rejected. When the iterable passed is empty, the promise returned will be forever pending.

The Promise.race() static method accepts a list or iterable of Promises (e.g.: Array) and returns a new Promise that resolves or rejects as soon as there is one promise that is fulfilled or rejects, with the value or error message from the promise.

Syntax: Promise.race(iterable);

The Promise.race() method accepts a list of promises/array of promises as an argument. The name of the Promise.race() method indicates that all the promises are raced against each other to win with a single winner that will be either resolve or rejected. Let’s walk through the example to understand the promise.race() method in deeply

Resolved Promise Example

Example1:

<html>
<head>
    <title>JavaScript Promise.race() resolved promises example1</title>
</head>
<body>
    <script>
        // wait "millis" ms, then resolve with "value"
        function resolve(value, milliseconds) {
            return new Promise((resolve, reject) => {
                setTimeout(() =>
                    resolve(value), milliseconds)
            });
        }
        // wait "millis" ms, then reject with "reason"
        function reject(reason, milliseconds) {
            return new Promise((resolve, reject) => {
                setTimeout(() =>
                    reject(reason), milliseconds)
            });
        }

        Promise.race([resolve(1, 5000), resolve(2, 3000), resolve(3, 1000)])
            .then(value => console.log(value)); // outputs "3" after 1 second.
    </script>
</body>
</html>

Output: 3

The above example prints the 3 after 1 second.

Example2:
<html>
<head>
    <title>JavaScript Promise.race() resolved promises example2</title>
</head>
<body>
    <script>
        const p1 = new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log('The first promise with 100 has resolved');
                resolve(100);
            }, 1 * 1000);

        });

        const p2 = new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log('The second promise with 200 has resolved');
                resolve(200);
            }, 2 * 1000);
        });


        Promise.race([p1, p2])
            .then(value => console.log(`Resolved: ${value}`))
            .catch(reason => console.log(`Rejected: ${reason}`));
    </script>
</body>
</html>

Output:

JavaScript Promise.race() vs Promise.all() with Examples

In the above 2nd example, we created two promised one resolves the 100 after 1 second while the second resolve the 200 after 2 seconds. Since the first promises resolve faster than the second promise. Hence the return promise will resolve with the value from the first promise that is 100.

Rejected Promise Example

Example1:

<html>
<head>
    <title>JavaScript Promise.race() reject promises example1</title>
</head>
<body>
    <script>
        // wait "millis" ms, then resolve with "value"
        function resolve(value, milliseconds) {
            return new Promise((resolve, reject) => {
                setTimeout(() =>
                    resolve(value), milliseconds)
            });
        }
        // wait "millis" ms, then reject with "reason"
        function reject(reason, milliseconds) {
            return new Promise((resolve, reject) => {
                setTimeout(() =>
                    reject(reason), milliseconds)
            });
        }

        Promise.race([reject(new Error('bad error!'), 6000), resolve(2, 2000)])
            .then(value => console.log(value)) // does not print anything
            .catch(error => console.log(error.message)); // outputs "bad error!" after 6 seconds
    </script>
</body>
</html>

Output: bad error!

The above example prints the bad error after 6 seconds once it finds the 1st settled promise regardless of whether it’s resolved or rejected.

Example2:
<html>
<head>
    <title>JavaScript Promise.race() rejected promises example2</title>
</head>
<body>
    <script>
        const p1 = new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log('The first promise with 100 has resolved');
                resolve(100);
            }, 1 * 1000);

        });

        const p2 = new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log('The second promise with 200 has rejected');
                reject(200);
            }, 2 * 1000);
        });


        Promise.race([p1, p2])
            .then(value => console.log(`Resolved: ${value}`))
            .catch(reason => console.log(`Rejected: ${reason}`));
    </script>
</body>
</html>

Output:

JavaScript Promise.race() vs Promise.all() with Examples

Note that if the second promise was faster than the first one, the return promise would reject with the reason for the second promise.

JavaScript Promise.race() vs. Promise.all()

The Promise.all() returns a promise that resolves to an array of values from the input promises while the Promise.race() returns a promise that resolves to the value from the first settled promise.

In the next article, I am going to discuss JavaScript Promise Error Handling with Examples. Here, in this article, I try to explain the JavaScript Promise.race() vs Promise.all() with Examples. I hope this JavaScript Promise.race() vs Promise.all() with Examples article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this JavaScript Promise.race() vs Promise.all() with Examples article.

Leave a Reply

Your email address will not be published.