InterviewHubPRO
Section Overview
Q483

Question 483 of 521

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

93%
JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

What is Promise.any and when should it be used?

Promise.any() is a Promise combinator method introduced in ES2021 that takes an iterable of promises and returns a single promise that fulfills as soon as any of the input promises fulfills. It resolves with the value of the first promise that successfully resolves.

Key Characteristics:

  1. First Success Wins: Returns the value of the first fulfilled promise
  2. Ignores Rejections: Continues waiting even if some promises reject
  3. AggregateError: Only rejects if all promises reject (with an AggregateError containing all rejection reasons)

When to Use Promise.any():

  • Fastest Resource: When fetching from multiple mirrors/CDNs and you want the first successful response
  • Redundant Services: When calling multiple redundant APIs and only need one to succeed
  • Fallback Mechanisms: When you have primary and backup data sources

Example:

javascript
 // Fetching from multiple CDNs - use whichever responds first
 const cdn1 = fetch('https://cdn1.example.com/data.json');
 const cdn2 = fetch('https://cdn2.example.com/data.json');
 const cdn3 = fetch('https://cdn3.example.com/data.json');

 Promise.any([cdn1, cdn2, cdn3])
   .then(response => response.json())
   .then(data => console.log('First successful response:', data))
   .catch(error => {
     // Only if ALL promises reject
     console.error('All CDNs failed:', error.errors);
   });

 // Comparison with other Promise methods:
 const promises = [
   Promise.reject('Error 1'),
   Promise.resolve('Success!'),
   Promise.reject('Error 2')
 ];

 // Promise.any() - Returns first fulfilled promise
 Promise.any(promises)
   .then(value => console.log(value)); // Output: "Success!"

 // Promise.race() - Returns first settled promise (fulfilled or rejected)
 Promise.race(promises)
   .catch(error => console.log(error)); // Output: "Error 1"

 // Promise.all() - Waits for all or fails on first rejection
 Promise.all(promises)
   .catch(error => console.log(error)); // Output: "Error 1"

 // Promise.allSettled() - Waits for all, never rejects
 Promise.allSettled(promises)
   .then(results => console.log(results));
 // Output: [
 //   { status: 'rejected', reason: 'Error 1' },
 //   { status: 'fulfilled', value: 'Success!' },
 //   { status: 'rejected', reason: 'Error 2' }
 // ]