Codectionary / Developer documentation / JavaScript

Promise.all(), allSettled(), race(), any()

These static methods handle multiple promises at once. Promise.all() waits for every promise to resolve, but rejects immediately if any one fails. allSettled() waits for all to finish regardless of outcome, giving you both successes and failures. race() resolves or rejects as soon as the first promise settles. any() resolves as soon as the first one succeeds, ignoring rejections unless all fail.

Syntax

Promise.all([p1, p2, p3])
Promise.allSettled([p1, p2, p3])

Examples

Promise.all() - All or Nothing

Running independent requests in parallel and waiting for all of them.

const userPromise = fetch("/api/user").then(r => r.json());
const postsPromise = fetch("/api/posts").then(r => r.json());

Promise.all([userPromise, postsPromise])
  .then(([user, posts]) => {
    console.log(user, posts);
  })
  .catch(error => {
    console.log("At least one request failed:", error.message);
  });

Promise.allSettled() - Getting Every Result

Useful when you need results from every promise, even if some fail.

const promises = [
  Promise.resolve("Success 1"),
  Promise.reject("Failure 1"),
  Promise.resolve("Success 2")
];

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

Best practices

  • Use Promise.all() when every operation must succeed for the result to be useful - like loading required page data
  • Use Promise.allSettled() when partial success is acceptable and you want to know exactly what failed without stopping the rest
  • Use Promise.race() for timeout patterns - race a real request against a promise that rejects after a delay
  • Avoid awaiting promises sequentially in a loop when they are independent - use Promise.all() with map() to run them in parallel instead

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation