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

We will learn about the Promise.any() method in JavaScript and how to use it with async/await. In JavaScript, promises handle asynchronous operations, making applications faster by allowing code execution without waiting for slow operations to complete.

What is Promise.any()?

The Promise.any() method returns the first successfully resolved promise from an array of promises. It ignores rejected promises and only fails if all promises are rejected (throwing an AggregateError).

Syntax

Promise.any(iterable)
  .then(value => {
    // Handle first resolved value
  })
  .catch(error => {
    // Handle AggregateError if all reject
  });

Parameters

  • iterable - An array of promises. The method returns the value of whichever promise resolves first.

Using Promise.any() with Async/Await

With async/await syntax, you can use Promise.any() more cleanly:

async function example() {
  try {
    const result = await Promise.any([promise1, promise2, promise3]);
    // Handle first resolved result
  } catch (error) {
    // Handle AggregateError if all promises reject
  }
}

Example: Basic Promise.any()

Here's a basic example showing how Promise.any() returns the first resolved promise:

<html>
<body>
  <h2>Using Promise.any() Method</h2>
  <div id="output"></div>
  <script>
    let promise1 = new Promise((resolve, reject) => {
      resolve("Promise 1: Resolved immediately");
    });
    
    let promise2 = new Promise((resolve, reject) => {
      reject("Promise 2: Rejected");
    });
    
    let promise3 = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("Promise 3: Resolved after 2 seconds");
      }, 2000);
    });
    
    Promise.any([promise1, promise2, promise3])
      .then(result => {
        document.getElementById("output").innerHTML = result;
      })
      .catch(error => {
        document.getElementById("output").innerHTML = "All promises rejected: " + error;
      });
  </script>
</body>
</html>

Example: Promise.any() with Async/Await and Fetch

This example demonstrates using Promise.any() with multiple API requests to get the fastest response:

<html>
<body>
  <h2>Promise.any() with Async/Await</h2>
  <button onclick="getFastestData()">Get Fastest API Response</button>
  <div id="output"></div>
  <script>
    async function getFastestData() {
      try {
        const requests = [
          fetch("https://jsonplaceholder.typicode.com/todos/1"),
          fetch("https://jsonplaceholder.typicode.com/todos/2"),
          fetch("https://jsonplaceholder.typicode.com/todos/3")
        ];
        
        const response = await Promise.any(requests);
        const data = await response.json();
        
        document.getElementById("output").innerHTML = 
          `<p>First response received:</p>
           <p>Status: ${response.status}</p>
           <p>Title: ${data.title}</p>`;
      } catch (error) {
        document.getElementById("output").innerHTML = 
          "All requests failed: " + error.message;
      }
    }
  </script>
</body>
</html>

Key Differences from Other Promise Methods

Method Behavior When to Use
Promise.all() Waits for all promises to resolve Need all results
Promise.race() Returns first settled (resolved OR rejected) Need fastest response (success or failure)
Promise.any() Returns first resolved promise Need fastest successful response

Common Use Cases

  • Multiple API endpoints: Try several servers and use whichever responds first
  • Resource loading: Load from multiple CDNs and use the fastest
  • Fallback mechanisms: Try primary service, fall back to secondary if needed

Conclusion

Promise.any() is perfect when you need the fastest successful result from multiple promises. Combined with async/await, it provides clean, readable code for handling race conditions between promises while ignoring failures.

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

969 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements