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

Promise.race() executes multiple promises concurrently and returns the result of whichever promise settles first, whether resolved or rejected. Unlike Promise.all(), it doesn't wait for all promises to complete.

Syntax

Promise.race(iterable)
  .then(result => {
    // Handle first settled promise
  })
  .catch(error => {
    // Handle if first promise rejected
  });

// With async/await
async function example() {
  try {
    const result = await Promise.race([promise1, promise2, promise3]);
    // Use result from first settled promise
  } catch (error) {
    // Handle error if first promise rejected
  }
}

Parameters

  • iterable: An array or other iterable object containing promises to race

Return Value

Returns a promise that settles with the value or rejection reason of the first promise that settles.

Example 1: Basic Promise.race() with Timers

This example shows how Promise.race() returns the first settled promise, even if it's rejected:

<html>
<body>
   <h2>Promise.race() with Different Timing</h2>
   <div id="output"></div>
   <script>
      let promise1 = new Promise((resolve, reject) => {
         setTimeout(() => {
            resolve("Promise 1 resolved after 1000ms");
         }, 1000);
      });

      let promise2 = new Promise((resolve, reject) => {
         reject("Promise 2 rejected immediately!");
      });

      let promise3 = new Promise((resolve, reject) => {
         setTimeout(() => {
            resolve("Promise 3 resolved after 2000ms");
         }, 2000);
      });

      Promise.race([promise1, promise2, promise3])
         .then(response => {
            document.getElementById("output").innerHTML = 
               "Race won by: " + response;
         })
         .catch(error => {
            document.getElementById("output").innerHTML = 
               "Race won by rejection: " + error;
         });
   </script>
</body>
</html>
Race won by rejection: Promise 2 rejected immediately!

Example 2: Using async/await with API Calls

This example demonstrates Promise.race() with async/await for API requests:

<html>
<body>
   <h2>Promise.race() with Async/Await and APIs</h2>
   <div id="output"></div>
   <button onclick="executeRace()">Race API Calls</button>
   <script>
      async function executeRace() {
         try {
            const requests = [
               fetch("https://api.publicapis.org/entries"),
               fetch("https://catfact.ninja/fact"),
               fetch("https://api.coindesk.com/v1/bpi/currentprice.json")
            ];

            const fastestResponse = await Promise.race(requests);
            document.getElementById("output").innerHTML = 
               "Fastest API: " + fastestResponse.url;
         } catch (error) {
            document.getElementById("output").innerHTML = 
               "Error: " + error.message;
         }
      }
   </script>
</body>
</html>

Example 3: Timeout Implementation

A common use case for Promise.race() is implementing timeouts:

function withTimeout(promise, timeoutMs) {
  const timeout = new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(new Error(`Operation timed out after ${timeoutMs}ms`));
    }, timeoutMs);
  });
  
  return Promise.race([promise, timeout]);
}

// Usage example
async function fetchWithTimeout() {
  try {
    const slowPromise = new Promise(resolve => {
      setTimeout(() => resolve("Data fetched!"), 3000);
    });
    
    const result = await withTimeout(slowPromise, 2000);
    console.log(result);
  } catch (error) {
    console.log("Caught:", error.message);
  }
}

fetchWithTimeout();
Caught: Operation timed out after 2000ms

Promise.race() vs Promise.any()

Method Returns Behavior on Rejection
Promise.race() First settled (resolved OR rejected) Rejects if first promise rejects
Promise.any() First resolved promise only Ignores rejections, waits for first success

Common Use Cases

  • Timeout handling: Race against a timeout promise
  • Fastest API response: Get data from the quickest server
  • Resource loading: Use the first available resource
  • Early cancellation: Stop when any condition is met

Conclusion

Promise.race() is ideal when you need the fastest response from multiple promises, regardless of success or failure. Use it for timeouts, performance optimization, and scenarios where the first settled promise is sufficient for your application needs.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements