JavaScript `Promise.any()`

2 min read .

JavaScript’s Promise.any() is a powerful method for working with multiple asynchronous operations. Unlike Promise.all() or Promise.race(), which resolve or reject based on the state of all promises or the first promise, Promise.any() resolves as soon as any of the provided promises resolves, making it a great choice when you need only one successful result.

What is Promise.any() in JavaScript?

Promise.any() takes an iterable of promises and returns a single promise that:

  • Resolves as soon as any of the input promises resolve.
  • Rejects only if all input promises are rejected.

This method is particularly useful when you are interested in the first successful result among several asynchronous operations.

Syntax:

Promise.any(iterable);
  • iterable: An iterable object such as an array containing multiple promises.

How Does Promise.any() Work?

Promise.any() works by returning a promise that fulfills or rejects based on the following conditions:

  • Resolves: When any of the promises in the iterable fulfills.
  • Rejects: With an AggregateError if all of the promises are rejected.

Examples of Using Promise.any()

  1. Basic Example of Promise.any()
const promise1 = Promise.reject('Error in promise1');
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'Resolved from promise2'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 200, 'Resolved from promise3'));

Promise.any([promise1, promise2, promise3])
  .then((value) => console.log(value))  // Output: "Resolved from promise2"
  .catch((error) => console.error(error));

Explanation:

  • promise1 is rejected immediately.
  • promise2 resolves after 100 milliseconds.
  • promise3 resolves after 200 milliseconds.
  • Since promise2 is the first to resolve, Promise.any() resolves with its value.
  1. Handling Rejection with AggregateError

If all promises are rejected, Promise.any() returns an AggregateError:

const promise1 = Promise.reject('Error in promise1');
const promise2 = Promise.reject('Error in promise2');

Promise.any([promise1, promise2])
  .then((value) => console.log(value))
  .catch((error) => console.error(error)); 
// Output: AggregateError: All promises were rejected
  1. Using Promise.any() for Fetch Requests

Promise.any() can be particularly useful when making multiple network requests, and you need the first successful response:

const fetch1 = fetch('https://jsonplaceholder.typicode.com/posts/1');
const fetch2 = fetch('https://jsonplaceholder.typicode.com/posts/2');
const fetch3 = fetch('https://jsonplaceholder.typicode.com/posts/3');

Promise.any([fetch1, fetch2, fetch3])
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error('All fetch requests failed:', error));

Benefits of Using Promise.any()

  • Optimized Performance: Reduces waiting time by resolving as soon as the first promise is fulfilled.
  • Improved User Experience: Enhances responsiveness by handling the first successful operation, especially in scenarios like fetching data from multiple servers.
  • Simpler Code: Provides a cleaner way to handle the “first-successful” scenario without manually iterating over promises.

When to Use Promise.any()?

  • Network Resilience: Fetching data from multiple sources and using the first successful response.
  • Fallback Strategies: Trying multiple fallbacks for an operation and using the first one that succeeds.
  • Race Conditions: Handling scenarios where you want the fastest response without waiting for others.

Browser Compatibility

Promise.any() is supported in most modern browsers, including Chrome (version 85+), Firefox (version 79+), and Safari (version 14+). However, it may not be supported in older browsers like Internet Explorer. Consider using a polyfill for broader compatibility.

Conclusion

JavaScript’s Promise.any() method offers a unique and efficient way to handle multiple asynchronous operations, resolving as soon as the first promise is fulfilled. It’s perfect for scenarios where you only need one successful outcome, improving performance and code simplicity.

See Also

chevron-up