Skip to content

Promise.allSettled and Any

This lesson explains Promise.allSettled and Any with clear examples, use cases, and best practices so you can use modern JavaScript confidently in real projects.

ES6+ Promise.allSettled and Promise.any Overview

Promise.allSettled() and Promise.any() are modern Promise combinators that solve different async problems. allSettled waits for every Promise to finish and reports both successes and failures, while any resolves with the first successful result.

These methods are useful when some requests may fail, when you need a complete result report, or when you want the fastest successful response from multiple sources such as mirrors, APIs, or CDN endpoints.

Feature Description
Promise.allSettled() Waits for all Promises to settle and returns every outcome.
Promise.any() Resolves with the first fulfilled Promise.
allSettled Introduced In ES2020
any Introduced In ES2021
allSettled Result Array of { status, value/reason } objects
any Failure Case Throws AggregateError if all Promises reject

Basic Promise.allSettled Example

const tasks = [
  Promise.resolve("User loaded"),
  Promise.reject(
    new Error("Orders failed")
  ),
  Promise.resolve("Settings loaded")
];

Promise.allSettled(tasks)
  .then((results) => {
    results.forEach((result) => {
      if (result.status === "fulfilled") {
        console.log("Success:", result.value);
      } else {
        console.log("Error:", result.reason.message);
      }
    });
  });

Unlike Promise.all(), allSettled never rejects early when one Promise fails. It waits for all operations to complete and gives you a full report.

How Promise.allSettled Works

Step Description Example
Pass Promises Provide an iterable of Promises. [p1, p2, p3]
Wait for All Every Promise must settle. Fulfilled or rejected
Collect Outcomes Build result objects for each Promise. status and value/reason
Return Array Resolve with full result list. results
Process Results Handle success and failure separately. forEach(...)

Promise.allSettled with Multiple API Calls

const endpoints = [
  fetch("/api/user"),
  fetch("/api/orders"),
  fetch("/api/notifications")
];

Promise.allSettled(endpoints)
  .then(async (results) => {
    const data = {};

    if (results[0].status === "fulfilled") {
      data.user =
        await results[0].value.json();
    }

    if (results[1].status === "fulfilled") {
      data.orders =
        await results[1].value.json();
    }

    if (results[2].status === "fulfilled") {
      data.notifications =
        await results[2].value.json();
    }

    console.log(data);
  });

This pattern is ideal for dashboards and profile pages where some sections can fail without breaking the entire page load.

Filter Successful Results from allSettled

const requests = [
  Promise.resolve({ id: 1 }),
  Promise.reject(new Error("Failed")),
  Promise.resolve({ id: 2 })
];

Promise.allSettled(requests)
  .then((results) => {
    const successful =
      results
        .filter(
          (item) =>
            item.status === "fulfilled"
        )
        .map((item) => item.value);

    console.log(successful);
  });

After allSettled completes, you can filter fulfilled results and continue working only with the successful values.

Basic Promise.any Example

const servers = [
  Promise.reject(new Error("Server A down")),
  Promise.resolve("Response from Server B"),
  Promise.resolve("Response from Server C")
];

Promise.any(servers)
  .then((result) => {
    console.log("First success:", result);
  })
  .catch((error) => {
    console.error(error.message);
  });

Promise.any() resolves as soon as one Promise fulfills. It ignores rejected Promises unless every Promise fails.

How Promise.any Works

Step Description Example
Pass Promises Provide multiple async operations. [p1, p2, p3]
Watch Results Wait for the first fulfilled Promise. Fastest success wins
Resolve Early Return the first successful value. result
Ignore Failures Rejected Promises are skipped individually. Until all fail
All Fail Reject with AggregateError. error.errors

Promise.any for Fastest Response

const mirrors = [
  fetch("https://mirror-a.example.com/data"),
  fetch("https://mirror-b.example.com/data"),
  fetch("https://mirror-c.example.com/data")
];

Promise.any(mirrors)
  .then((response) => response.json())
  .then((data) => {
    console.log("Fastest mirror:", data);
  })
  .catch((error) => {
    console.error(
      "All mirrors failed",
      error.errors
    );
  });

Use Promise.any() when multiple sources provide the same data and you only need the first successful response.

Handling AggregateError

const failingTasks = [
  Promise.reject(new Error("Task 1 failed")),
  Promise.reject(new Error("Task 2 failed")),
  Promise.reject(new Error("Task 3 failed"))
];

Promise.any(failingTasks)
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.log(error.name);
    console.log(error.message);

    error.errors.forEach((err) => {
      console.log(err.message);
    });
  });

When every Promise rejects, Promise.any() throws an AggregateError. Its errors array contains all rejection reasons.

Promise Combinator Comparison

Method Resolves When Rejects When Best For
Promise.all() All Promises fulfill Any Promise rejects All tasks must succeed
Promise.allSettled() All Promises settle Never rejects Full success/failure report
Promise.race() First Promise settles First Promise rejects First finished result
Promise.any() First Promise fulfills All Promises reject First successful result

Promise.race vs Promise.any

const slowSuccess =
  new Promise((resolve) =>
    setTimeout(
      () => resolve("Slow success"),
      1000
    )
  );

const fastFailure =
  Promise.reject(
    new Error("Fast failure")
  );

Promise.race([
  slowSuccess,
  fastFailure
]).catch((error) => {
  console.log("race:", error.message);
});

Promise.any([
  slowSuccess,
  fastFailure
]).then((result) => {
  console.log("any:", result);
});

race returns the first settled Promise, even if it fails. any waits for the first success and ignores individual failures until all Promises reject.

Using allSettled and any with async/await

async function loadDashboard() {
  const results =
    await Promise.allSettled([
      fetch("/api/user"),
      fetch("/api/stats"),
      fetch("/api/alerts")
    ]);

  const successful =
    results.filter(
      (item) =>
        item.status === "fulfilled"
    );

  return successful.length;
}

async function loadFastestConfig() {
  try {
    const response =
      await Promise.any([
        fetch("/config/a.json"),
        fetch("/config/b.json")
      ]);

    return response.json();
  } catch (error) {
    console.error(
      "No config source worked"
    );
    throw error;
  }
}

Both methods work naturally with async/await, which often makes result handling easier to read in application code.

Common Use Cases

  • allSettled — dashboard widgets that load independently.
  • allSettled — batch uploads where some files may fail.
  • allSettled — reporting all validation results at once.
  • any — requesting data from multiple mirrors or CDNs.
  • any — trying backup APIs when the primary source is slow.
  • any — failover logic for external services.

Best Practices

  • Use allSettled when partial failure is acceptable.
  • Use any when you only need one successful result.
  • Check result.status before reading value or reason.
  • Handle AggregateError when using Promise.any().
  • Do not use any when every result matters.
  • Do not use allSettled when one failure should stop the whole workflow.
  • Prefer async/await for complex result processing logic.

Common Mistakes

  • Using Promise.all() when some failures should be tolerated.
  • Assuming allSettled rejects when one Promise fails.
  • Using race instead of any for failover logic.
  • Forgetting to inspect AggregateError.errors.
  • Reading result.value without checking status.
  • Expecting any to return all successful results.
  • Not handling empty iterables passed to combinator methods.

Key Takeaways

  • Promise.allSettled() waits for every Promise and reports all outcomes.
  • Promise.any() resolves with the first fulfilled Promise.
  • allSettled is ideal for partial success scenarios.
  • any is ideal for fastest-success and failover patterns.
  • Choose the combinator based on whether you need all results, first finish, or first success.

Pro Tip

For dashboard pages, use Promise.allSettled() to load sections independently. For backup API requests, use Promise.any() to accept the first working response.