Promise.any() is a promise concurrency method that takes an iterable of Promise objects and returns a single Promise. This returned promise fulfills as soon as any of the input promises fulfills, with the value of that first fulfilled promise.

1. How It Works

If you have multiple asynchronous tasks running simultaneously, Promise.any() ignores the ones that fail (reject) and only waits for the first one that succeeds (fulfills).

Key Differences:

  • Success: It returns the value of the first promise to fulfill.

  • Failure: It only rejects if all input promises reject.

  • Error Handling: If all promises fail, it throws an AggregateError—a special error object that groups together all individual errors.


2. Basic Syntax

JavaScript

Promise.any(iterable);

Example: First Successful Request

Imagine you are fetching data from three different mirror servers. You don’t care which one responds first, as long as you get the data.

JavaScript

const p1 = new Promise((resolve, reject) => setTimeout(reject, 100, 'Server A failed'));
const p2 = new Promise((resolve) => setTimeout(resolve, 200, 'Server B success'));
const p3 = new Promise((resolve) => setTimeout(resolve, 300, 'Server C success'));

Promise.any([p1, p2, p3])
  .then((value) => console.log(value))
  .catch((error) => console.error(error));

// Output: "Server B success" 
// (Even though Server A finished first, it failed, so Promise.any ignored it)

3. When All Promises Fail

If every promise in the list is rejected, Promise.any() rejects with an AggregateError. You can access the specific error messages using the .errors property.

JavaScript

const p1 = Promise.reject('Error 1');
const p2 = Promise.reject('Error 2');

Promise.any([p1, p2]).catch((err) => {
  console.log(err.name);    // "AggregateError"
  console.log(err.errors);  // ["Error 1", "Error 2"]
});

4.Example: Multi-Server Fetch

Imagine you have a file hosted on three different global mirrors. You don’t care which one responds, as long as you get the file as quickly as possible. If one server is down (rejects), you want to wait for the others.

JavaScript

const request1 = fetch('https://server-a.com/data.json');
const request2 = fetch('https://server-b.com/data.json');
const request3 = fetch('https://server-c.com/data.json');

Promise.any([request1, request2, request3])
  .then((firstSuccessfulResponse) => {
    console.log('Received data from the fastest healthy server:', firstSuccessfulResponse);
  })
  .catch((error) => {
    // This only runs if ALL three fetches fail
    console.error('All mirrors failed:', error.errors);
  });

5.Example: Loading an Image

If you have multiple sources for an image (a primary URL and a backup), you can use Promise.any() to display whichever one loads successfully first.

JavaScript

async function loadImage(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error('Could not load');
  return response.blob();
}

try {
  const fastestImage = await Promise.any([
    loadImage('https://primary-server.com/img.png'),
    loadImage('https://backup-server.com/img.png')
  ]);
  // Use the image blob...
} catch (e) {
  console.log("None of the images could be loaded.");
}

Categorized in:

Javascript,