Promises.any() in JavaScript

✨ What is Promise.any()?

Promise.any() returns a promise that fulfills as soon as any one of the promises in the iterable is fulfilled. It ignores all rejected promises and only fails if all promises are rejected.

>>“Just give me the first success, I don’t care who fails.”

📦 Syntax

Code Snippet

Promise.any([promise1, promise2, promise3])
  .then((value) => {
    // First successful value
  })
  .catch((error) => {
    // All promises rejected
  });

🚀 Example: First Success Wins

First Fulfilled Promise

const p1 = new Promise((_, reject) => setTimeout(() => reject("❌ p1 failed"), 300));
const p2 = new Promise((resolve) => setTimeout(() => resolve("✅ p2 success"), 500));
const p3 = new Promise((resolve) => setTimeout(() => resolve("✅ p3 success"), 800));

Promise.any([p1, p2, p3])
  .then((result) => {
    console.log("Result:", result); // ✅ p2 success
  })
  .catch((error) => {
    console.error("All failed:", error);
  });

Note

✅ The first fulfilled promise resolves the whole thing, no matter how many others fail.

⛔ What if All Fail?

If every promise in the array rejects, Promise.any() rejects with an AggregateError that holds all rejection reasons.

All Fail Scenario

const a = Promise.reject("❌ Error A");
const b = Promise.reject("❌ Error B");

Promise.any([a, b])
  .then((value) => console.log("Success:", value))
  .catch((err) => {
    console.error("All failed:", err); // AggregateError: All promises were rejected
    console.log("Details:", err.errors); // ["❌ Error A", "❌ Error B"]
  });

Note

🧠 AggregateError is a special error object containing an errors array.

⚙ Use Case: Fallback Strategy

Use Promise.any() when you want to try multiple fallback methods and settle on the first one that works.

CDN Fallback Example

const loadFromCDN1 = () => fetch("https://cdn1.example.com/lib.js");
const loadFromCDN2 = () => fetch("https://cdn2.example.com/lib.js");
const loadFromCDN3 = () => fetch("https://cdn3.example.com/lib.js");

Promise.any([loadFromCDN1(), loadFromCDN2(), loadFromCDN3()])
  .then((res) => res.text())
  .then((script) => {
    console.log("Loaded script from first available CDN");
    // Do something with script
  })
  .catch((err) => {
    console.error("❌ All CDN sources failed", err);
  });

🧠 Key Points

  • Resolves as soon as one promise fulfills.
  • Rejects only if all promises are rejected.
  • Rejection gives an AggregateError object.
  • Perfect for "first success wins" or fallback-based logic.

📚 References

>>“Be optimistic: one success is all you need.”