Table of Contents

Introduction

JavaScript Promise.any() is a static Promise method that fulfills as soon as any one of the promises in an iterable fulfills. It is useful when an application can accept the result from whichever asynchronous operation succeeds first, such as requesting data from several servers, trying alternative services, or loading a resource from multiple sources.

Unlike Promise.race(), which settles as soon as the first input promise settles (whether fulfilled or rejected), Promise.any() waits for the first fulfilled promise. A rejection does not stop the other operations. If every input promise rejects, the returned promise rejects with an AggregateError containing the reasons for all the failures.

What Is Promise.any() in JavaScript?

The Promise.any() method accepts an iterable, usually an array, of promises or other values. It returns a new promise that fulfills with the value from the first input that fulfills. The method was introduced in ECMAScript 2021 (ES12).

Its key behavior is simple:

  • If at least one input fulfills, the returned promise fulfills with that value.
  • If an input rejects, JavaScript continues waiting for the remaining inputs.
  • If all inputs reject, the returned promise rejects with an AggregateError.
  • If the iterable is empty, the returned promise rejects with an AggregateError because no input can fulfill.

This makes Promise.any() a good choice when success from one source is enough and failures from other sources can be ignored unless every source fails.

Syntax of Promise.any()

Promise.any(iterable);

iterable: An iterable object, such as an array, containing promises or values. Each value is internally treated like a promise through the Promise resolution process.

Return value: A promise that fulfills with the first fulfillment value, or rejects with an AggregateError when all input promises reject (including when the iterable is empty).

Basic Example of Promise.any()

In the following example, three promises complete at different times. The first promise rejects, the second fulfills, and the third fulfills later. The returned promise uses the value from the second promise because it is the first one to fulfill.

const first = new Promise((resolve, reject) => {
  setTimeout(() => reject("First request failed"), 500);
});

const second = new Promise((resolve) => {
  setTimeout(() => resolve("Second request succeeded"), 1000);
});

const third = new Promise((resolve) => {
  setTimeout(() => resolve("Third request succeeded"), 1500);
});

Promise.any([first, second, third])
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.error(error);
  });

Output:

Second request succeeded

The first rejection does not determine the result. JavaScript keeps waiting until the second promise fulfills. Once that happens, the result of Promise.any() is fulfilled with the second promise’s value.

How Promise.any() Handles Rejected Promises

A rejected input promise is not immediately passed to the catch handler of the returned promise. Instead, Promise.any() records the rejection reason and checks the other inputs. This is important when several independent services can provide the same kind of result.

const tasks = [
  Promise.reject("Server A is unavailable"),
  Promise.reject("Server B returned an error"),
  Promise.resolve("Server C returned the data")
];

Promise.any(tasks)
  .then((value) => {
    console.log(value);
  })
  .catch((error) => {
    console.error(error);
  });

Output:

Server C returned the data

Although two promises reject, one promise fulfills. Therefore, the returned promise fulfills with "Server C returned the data". The earlier failures do not prevent a successful result.

Handling AggregateError When All Promises Reject

If every input promise rejects, there is no fulfillment value to return. In that situation, Promise.any() rejects with an AggregateError. This error groups the individual rejection reasons in its errors property.

const requests = [
  Promise.reject("Connection timeout"),
  Promise.reject("Access denied"),
  Promise.reject("Service unavailable")
];

Promise.any(requests)
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.log(error instanceof AggregateError); // true
    console.log(error.errors);
  });

Output:

true
[
  "Connection timeout",
  "Access denied",
  "Service unavailable"
]

You can inspect each reason to understand why all operations failed. The errors array follows the order of the input iterable, not necessarily the chronological order in which the promises rejected.

For a more descriptive error message, you can also inspect error.name and error.message. The message commonly indicates that all promises were rejected, while error.errors contains the individual reasons.

Using Promise.any() with async/await

You can use Promise.any() inside an async function and wait for its result with await. This style is useful when the rest of your code needs to run after one of several asynchronous operations succeeds.

async function loadFromAvailableService() {
  const services = [
    fetch("/api/primary-data"),
    fetch("/api/backup-data"),
    fetch("/api/replica-data")
  ];

  try {
    const response = await Promise.any(services);

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    if (error instanceof AggregateError) {
      console.error("Every service request failed:", error.errors);
    } else {
      console.error("Could not process the response:", error);
    }
  }
}

loadFromAvailableService();

This example sends requests to three endpoints and continues when the first request promise fulfills. Note that fetch() normally fulfills for HTTP responses such as 404 or 500; it rejects mainly for network-level failures. If an HTTP error response should count as a failed candidate, validate response.ok inside each candidate promise before passing it to Promise.any().

function fetchSuccessfulResponse(url) {
  return fetch(url).then((response) => {
    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }

    return response;
  });
}

const sources = [
  fetchSuccessfulResponse("/api/primary"),
  fetchSuccessfulResponse("/api/backup"),
  fetchSuccessfulResponse("/api/replica")
];

Promise.any(sources)
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error.errors));

Promise.any() with Values Instead of Promises

The iterable does not have to contain only promise objects. You can pass ordinary values too. JavaScript treats each value as an already fulfilled promise, so a non-promise value can fulfill the returned promise immediately.

Promise.any([
  Promise.reject("Request failed"),
  "Available immediately",
  Promise.resolve("Another result")
])
  .then((result) => console.log(result));

Output:

Available immediately

Because the string is not a promise, it is treated as a fulfilled value. It can therefore win before a slower asynchronous promise fulfills.

Promise.any() with an Empty Array

An empty iterable has no promise that can fulfill. As a result, Promise.any([]) returns a rejected promise with an AggregateError.

Promise.any([])
  .then((value) => console.log(value))
  .catch((error) => {
    console.log(error instanceof AggregateError); // true
    console.log(error.errors); // []
  });

The errors property is an empty array because there were no input promises and therefore no individual rejection reasons.

Promise.any() vs Promise.race()

Both methods accept an iterable of promises and return a new promise, but they use different rules to decide when the result settles.

Feature Promise.any() Promise.race()
Success condition First fulfilled input First settled input
When an input rejects Waits for other inputs Can reject the returned promise immediately
All inputs reject Rejects with AggregateError Rejects with the first rejection to settle
Empty iterable Rejects with AggregateError Remains pending
Typical purpose Accept one successful result Use whichever result settles first

For example, if a fast request rejects after 200 milliseconds and another request fulfills after 700 milliseconds, Promise.race() rejects after 200 milliseconds. Promise.any() ignores that first rejection and fulfills after 700 milliseconds with the successful result.

Promise.any() vs Promise.all()

Promise.all() and Promise.any() solve different problems. Use Promise.all() when every operation must fulfill before you can continue. It fulfills with an array of results when all inputs fulfill, and rejects as soon as an input rejects. Use Promise.any() when one successful operation is sufficient.

const tasks = [
  fetch("/api/profile"),
  fetch("/api/settings"),
  fetch("/api/notifications")
];

// All three operations must fulfill.
const allResults = await Promise.all(tasks);

// Only one successful operation is required.
const firstSuccess = await Promise.any(tasks);

The two methods should not be treated as interchangeable. Choose based on whether your application needs every result or only one successful result.

Managing Requests That Continue After Promise.any() Fulfills

When one promise fulfills, Promise.any() settles its returned promise, but it does not automatically cancel the other operations. Those requests may continue running and consume network, CPU, or server resources. If the remaining work is no longer useful, use an API that supports cancellation, such as fetch() with AbortController.

const controller = new AbortController();
const signal = controller.signal;

const urls = [
  "/api/primary",
  "/api/backup",
  "/api/replica"
];

const requests = urls.map((url) =>
  fetch(url, { signal }).then((response) => {
    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }
    return response;
  })
);

Promise.any(requests)
  .then((response) => {
    controller.abort(); // Stop requests that are still in progress.
    return response.json();
  })
  .then((data) => console.log(data))
  .catch((error) => {
    if (error instanceof AggregateError) {
      console.error("All endpoints failed:", error.errors);
    } else {
      console.error(error);
    }
  });

Aborting the shared controller after a successful response can stop other in-progress fetch requests. The winning request has already completed, so its response can still be processed. Use cancellation only when the remaining operations are genuinely unnecessary; if you need their results for logging, caching, or another task, allow them to finish instead.