Course contentsShow
← JavaScript
Lesson 1318 of 2,72329. PromisesFree lesson

Promise.any for Redundancy and Fallbacks

Apply any when you have multiple sources and only need one successful result.

Promise.any for Redundancy and Fallbacks

What you'll learn: How to use Promise.any() to implement resilient systems with backup options.

The Core Idea

When you have multiple ways to get the same data—say, multiple API endpoints or mirror servers—you want the first successful result, not just the fastest (which might be an error). Promise.any() is perfect for this redundancy pattern: you race several sources, take the first one that succeeds, and only fail if all fail.

Real-World Analogy

Imagine ordering food from three different apps simultaneously because your friends are starving. You don't care which app delivers first—you just want someone to deliver successfully. If all three fail, only then do you give up.

Redundancy Pattern

const fetchFromPrimary = fetch('https://api-primary.com/data');
const fetchFromBackup1 = fetch('https://api-backup1.com/data');
const fetchFromBackup2 = fetch('https://api-backup2.com/data');

Promise.any([fetchFromPrimary, fetchFromBackup1, fetchFromBackup2])
  .then(response => response.json())
  .then(data => console.log('Got data from fastest successful source:', data))
  .catch(error => console.error('All sources failed:', error));

Even if fetchFromPrimary rejects immediately, Promise.any() waits for the backups. Your app gets data as long as at least one source succeeds.

Fallback Chain

Promise.any([
  cache.get('user-data'),           // Try cache first
  database.query('SELECT * ...'),   // Then database
  externalAPI.fetch('/user')        // Finally external API
])
  .then(userData => console.log('Retrieved from somewhere:', userData));

This tries the fastest/cheapest option first but gracefully falls back to more expensive sources.

Key Takeaway: Use Promise.any() when you have multiple sources for the same data and want the first successful result, making your application resilient to individual failures.