Explain Promise.race() with async-await in JavaScript?


We will learn about the Promise.race() method in this tutorial. As the name of the race() method suggests, promises passed as a parameter of the race() method do the race to execute.

So, Whichever promise will be resolved first, will be executed only by the race() method, and other promises will never be executed.

Promise.race()

The Promise.race method in JavaScript allows you to wait for the first of a set of promises to be fulfilled or rejected, and to handle the result or error that occurs. It returns a promise that is fulfilled or rejected as soon as one of the input promises is fulfilled or rejected, with the value or reason from that promise.

Users can follow the syntax below to use the promise.race() method to execute the first settled promise.

Promise.race(iterable).then((response) => {
   // handle response
});

In the above syntax, the Promise.race() method takes the iterable as a first parameter, and we can handle the response of the successfully executed promise inside the ’then’ block.

here iterable takes the iterable objects, such as an array of promises to execute any promise from them, which settles first.

Syntax

Following is a syntax of how you might use the Promise.race method with async-await in JavaScript:

async function example() {
   try {
      const result = await Promise.race([promise1, promise2, ...]);
   } catch (error) {
      // handle error
   }
}

Here, promise1, promise2, and so on are promises that you want to wait for. The Promise.race method returns a promise that is resolved or rejected with the value or reason of the first input promise to be resolved or rejected.

The async function example uses the try/catch statement to handle the error case, where the catch block is executed if any of the input promises are rejected.

Example 1

In this example, we have created multiple promises and set up the timer inside the promises to resolve or reject them. We have passed the array of promises as the parameter of the race() method.

The output shows that the race() method executes the rejected promise as it has no timer. So, the race() method executes the first promise, which is fulfilled early, even if rejected or resolved.

<html>
<body>
   <h2>Using the Promise.race() </i> Method </h2>
   <div id="output"></div>
   <script>
      let promise_1 = new Promise((res, rej) => {
         setTimeout(() => {
            res("Resolved promise with time of 0 milliseconds");
         }, 1000);
      });
      let promise_2 = new Promise((res, rej) =>
      rej("This promise is rejected!")
      );
      let promise_3 = new Promise((res, rej) => {
         setTimeout(() => {
            res("Resolved promise with time of 2000 milliseconds");
         }, 2000);
      });
      Promise.race([promise_1, promise_2, promise_3]).then(
         (response) => {
            document.getElementById("output").innerHTML +=
            "Promise resolved successfully.";
         },
         (error) => {
            document.getElementById("output").innerHTML += "Promise rejected";
         }
      );
   </script>
</body>
</html>

Example 2

In this example, we have taken the different APIs and made a promise using the fetch method. We have an array of promises named requests.

We used the race() method to resolve all requests, and whichever promise will resolve first, we printed the URL inside the ‘then’ block.

<html>
<body>
   <h2>Using Promise.race() Method with async-await</h2>
   <div id = "output"> </div>
   <button onclick = "executeRace()"> Fetch data from early promise </button>
   <script>
      async function executeRace() {
         // array of different promises
         const requests = [
            fetch("https://api.publicapis.org/entries"),
            fetch("https://catfact.ninja/fact"),
            fetch("https://api.coindesk.com/v1/bpi/currentprice.json"),
         ];
         // resolving the promises using the race() method
         const res = await Promise.race(requests);
         document.getElementById("output").innerHTML +=
         "The first promise resolve is " + res.url;
      }
   </script>
</body>
</html>

Users can use the race() method when they need to use the responses from the first settled promise, even if rejected or resolved. If users need to use the result of the first successfully resolved promise, they should use the promise.any() method.

Updated on: 29-Dec-2022

931 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements