← Tous les articles

JavaScript: Promise.all vs allSettled vs race vs any — running requests in parallel and handling failures

Four ways to combine promises, four different reactions to a failure. When to use Promise.all, Promise.allSettled, Promise.race and Promise.any, with realistic fetch-based examples, cancelling the requests that are still running, and a small helper to cap how many requests run at once.

JavaScript: Promise.all vs allSettled vs race vs any — running requests in parallel and handling failures

Key points

  • Promise.all fails on the first error: use it when you need every result.
  • Promise.allSettled waits for everything and reports both successes and failures, which suits independent blocks such as dashboard widgets.
  • Promise.race settles with the first result, success or error; Promise.any with the first success. For timeouts, reach for AbortSignal.timeout() instead.

When a page needs several independent resources, awaiting them one after another makes the user wait for nothing: the total time becomes the sum of every request. The fix is to run them in parallel, and JavaScript gives you four tools for that: Promise.all, Promise.allSettled, Promise.race and Promise.any. They look alike but behave very differently when one request fails. Pick the wrong one and either a single broken widget takes the whole page down, or errors vanish without a trace. Here’s how to choose, along with the traps we keep catching in code review.

Sequential vs parallel: where the problem starts

The examples below use a small getJSON helper. It does one important thing: it throws on 404 or 500 responses, which fetch doesn’t do on its own.

async function getJSON(url, options = {}) {
  const res = await fetch(url, options);
  if (!res.ok) throw new Error(`${res.status} on ${url}`);
  return res.json();
}

Now compare two ways of loading three resources:

// Sequential: each request waits for the previous one
const profile = await getJSON('/api/profile');
const orders = await getJSON('/api/orders');
const notifications = await getJSON('/api/notifications');

// Parallel: all three start at once
const [profile2, orders2, notifications2] = await Promise.all([
  getJSON('/api/profile'),
  getJSON('/api/orders'),
  getJSON('/api/notifications'),
]);

In the first version, if each request takes just under a second, the user waits nearly three seconds. In the second, they wait as long as the slowest one. The gain only exists when the requests are independent: if the second needs an ID returned by the first, they have to stay sequential.

A mistake we see often in review: putting await inside forEach or a for loop and expecting it to run in parallel. To fire several requests at once, create all the promises first, with map for instance, and then await them together.

Promise.all: all or nothing

Promise.all waits for every promise to fulfil and returns the results in the same order as the input array, whatever order they arrived in. But if a single one rejects, the combined promise rejects straight away with that error and the other results are lost.

It’s the right choice when the whole only makes sense complete: rendering an invoice that needs the customer, the line items and the taxes, or saving several linked records. Keep in mind that the rejection doesn’t stop the other requests; they keep running in the background. If they’re expensive, cancel them with a shared AbortController:

const controller = new AbortController();
try {
  const results = await Promise.all(
    urls.map((url) => getJSON(url, { signal: controller.signal }))
  );
  render(results);
} catch (err) {
  controller.abort(); // no point letting the other requests run
  showError(err);
}

Another trap: a rejected promise that is never awaited triggers an “Uncaught (in promise)” warning. If you create promises up front and only await some of them, or return from the function before the await, those errors are left dangling.

Promise.allSettled: every result counts, including failures

Promise.allSettled never rejects. It waits for every promise to finish and returns, for each one, either { status: 'fulfilled', value } or { status: 'rejected', reason }. It is our default on dashboards: if the reviews widget breaks, there is no reason to hide the sales figures from the user.

const widgets = ['sales', 'stock', 'reviews'];
const results = await Promise.allSettled(
  widgets.map((w) => getJSON(`/api/dashboard/${w}`))
);

results.forEach((r, i) => {
  if (r.status === 'fulfilled') {
    renderWidget(widgets[i], r.value);
  } else {
    renderUnavailable(widgets[i]);
    console.warn(widgets[i], r.reason);
  }
});

The flip side is that failures are easy to ignore. With allSettled, an error interrupts nothing and shows up nowhere unless you explicitly handle the rejected case. At least render an “unavailable” state in the UI and send the error to your monitoring tool.

It also fits batch jobs: send notifications to a list of recipients, then report “47 sent, 3 failed” with the failures listed so they can be retried.

Promise.race and Promise.any: first one wins

Promise.race settles with whichever promise finishes first, fulfilled or rejected. Its classic use was enforcing a timeout on a request. That technique has a flaw: when the timer wins, the request isn’t cancelled; it keeps going and keeps using the network. With fetch, AbortSignal.timeout(), available in current browsers and in Node.js, does better:

// Old approach: race against a timer
function timeout(ms) {
  return new Promise((_, reject) =>
    setTimeout(() => reject(new Error('Timed out')), ms));
}
const data = await Promise.race([getJSON('/api/slow'), timeout(5000)]);

// Current approach: the request is actually cancelled
const data2 = await getJSON('/api/slow', { signal: AbortSignal.timeout(5000) });

The timeout signal rejects with an error named TimeoutError, so you can show a specific message rather than a generic server error. race is still useful for other contests, such as a response versus a user action that makes it pointless.

Promise.any waits for the first success and ignores failures while there’s still a chance. It only rejects when every promise fails, with an AggregateError whose errors property holds each error. It’s made for redundant sources: two config servers, a fallback mirror.

try {
  const config = await Promise.any([
    getJSON('https://cdn-a.example.com/config.json'),
    getJSON('https://cdn-b.example.com/config.json'),
  ]);
  start(config);
} catch (err) {
  // AggregateError : every source failed
  console.error(err.errors);
  start(DEFAULT_CONFIG);
}

Careful: with any, the losing requests keep running too. If the sources are expensive, cancel them once you have a winner.

Don’t launch everything at once: capping concurrency

Running three requests in parallel is harmless. Running three hundred, say uploading a gallery or syncing a catalogue, can saturate the connection, hit an API’s rate limit or overload your own server. None of the four methods limits how many tasks run at once; they only wait on promises that have already started. A short helper is enough to keep, for example, at most four uploads in flight:

// Run tasks with at most `limit` in flight at a time
async function mapWithLimit(items, limit, task) {
  const results = new Array(items.length);
  let next = 0;

  async function worker() {
    while (next < items.length) {
      const i = next++;
      try {
        results[i] = { status: 'fulfilled', value: await task(items[i]) };
      } catch (reason) {
        results[i] = { status: 'rejected', reason };
      }
    }
  }

  await Promise.all(
    Array.from({ length: Math.min(limit, items.length) }, worker)
  );
  return results; // same shape as Promise.allSettled
}

// 300 images to upload, at most 4 at a time
const report = await mapWithLimit(files, 4, uploadImage);

Each “worker” picks up the next item as soon as it finishes the previous one; because JavaScript is single-threaded, incrementing next is safe. The result has the same shape as allSettled‘s, so you can reuse the same rendering code. Base the limit on what the target API tolerates rather than on a universal number.

FAQ

Does Promise.all actually run the requests in parallel?

Requests start when the promises are created, not when Promise.all is called; Promise.all only waits. That’s why urls.map(url => fetch(url)) fires everything immediately, while a loop with await inside stays sequential.

What happens with an empty array?

Promise.all and Promise.allSettled resolve immediately with an empty array. Promise.any rejects immediately with an AggregateError. Promise.race never settles at all, so check the length first if the array can be empty.

Slow-loading app, or errors that disappear without a trace? We audit and optimise the JavaScript in your websites and web applications, from request handling to error monitoring.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →