Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 4 · Lesson 36 · 5 min read

JavaScript Promises Explained: all vs allSettled

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Loading a Dashboard with the Right Combinator
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Explain what a promise represents, its states and how then chains transform values and errors, create promises around callback APIs, and choose correctly between Promise.all, allSettled, race and any for concurrent work, while avoiding unhandled rejections.

Concept Explanation

A promise is an object representing a value that will be available later, or an error explaining why it never will be. It starts pending and settles exactly once, either fulfilled with a value or rejected with a reason. Once settled it never changes, and any number of consumers can attach handlers before or after it settles. That makes promises far easier to compose than the callbacks they replaced, where every function had its own conventions for errors and nothing stopped a callback from being called twice.

The then method registers handlers and returns a new promise, which is what makes chaining work. Whatever a handler returns becomes the fulfillment value of the next promise in the chain. If a handler returns another promise, the chain waits for it. If a handler throws, the next promise rejects. So a chain behaves like synchronous code that flows top to bottom, with catch acting like a catch block that handles any rejection above it, and finally running cleanup regardless of the outcome. Remember from Day 5 that promise handlers always run as microtasks, never synchronously, even when the promise is already settled.

You rarely need the Promise constructor, because most modern APIs already return promises. It is useful for wrapping old callback-based APIs or events: new Promise((resolve, reject) => ...) gives you the two functions that settle the promise. A common mistake, called the explicit construction antipattern, is wrapping a function that already returns a promise in a new Promise, which adds code and often loses errors. Promise.withResolvers, added in ECMAScript 2024, returns the promise together with its resolve and reject functions, which is handy when settlement happens somewhere other than the constructor callback.

Combinators handle several promises at once. Promise.all waits for all to fulfill and rejects as soon as any rejects, which suits requests that are all required, such as a page that needs a user and their settings. Promise.allSettled waits for every promise and reports each outcome, which suits independent work where partial success is useful, such as loading dashboard widgets. Promise.race settles with whichever settles first, the classic way to add a timeout. Promise.any fulfills with the first success and only rejects if all fail, which suits trying mirrors or fallbacks. Starting the operations before awaiting them is what makes them concurrent; the combinator only decides how to wait.

A rejected promise with no handler is an unhandled rejection. Browsers report it in the console and fire an unhandledrejection event, and monitoring tools capture it; in Node.js it crashes the process by default. Every chain must end in a catch, or be awaited inside a try block, or be returned to a caller who handles it. Silently swallowing errors with an empty catch is not handling them.

APISettles whenTypical use
then and catchEach step finishesSequential transformations
finallyAfter either outcomeHide a spinner, release a lock
Promise.allAll fulfill, or first rejectionRequired parallel requests
Promise.allSettledEvery promise settlesIndependent widgets, partial success
Promise.raceFirst to settleTimeouts
Promise.anyFirst fulfillment, or all rejectMirrors and fallbacks
new PromiseWhen resolve or reject is calledWrapping callback and event APIs
Promise.withResolversExposes resolve and rejectSettling from elsewhere

Worked Example: Loading a Dashboard with the Right Combinator

The page needs the user to render at all, but each widget is independent. The image preloader wraps an event-based API in a promise.

JavaScript
const getJSON = (url) => fetch(url).then((r) => {
  if (!r.ok) throw new Error(`${url} failed with ${r.status}`);
  return r.json();
});

// Required data: fail fast if either request fails
const [user, settings] = await Promise.all([getJSON('/api/me'), getJSON('/api/settings')]);

// Independent widgets: render whatever succeeded
const widgets = ['sales', 'traffic', 'tickets'];
const results = await Promise.allSettled(widgets.map((w) => getJSON(`/api/widgets/${w}`)));
results.forEach((r, i) => {
  if (r.status === 'fulfilled') renderWidget(widgets[i], r.value);
  else renderWidgetError(widgets[i], r.reason.message);
});

// Wrapping an event API in a promise
function loadImage(src) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error(`Could not load ${src}`));
    img.src = src;
  });
}

// A timeout with race (Day 37 shows AbortSignal.timeout, which also cancels the request)
const timeout = (ms) => new Promise((_, reject) => setTimeout(() => reject(new Error('Timed out')), ms));
const avatar = await Promise.race([loadImage(user.avatarUrl), timeout(3000)])
  .catch(() => loadImage('/img/default-avatar.png'));

// Last line of defense: report anything that slipped through
window.addEventListener('unhandledrejection', (e) => reportError(e.reason));

Notice that the widget requests start inside map before allSettled is awaited, so all three run in parallel. Awaiting them one by one in a loop would have taken the sum of their durations instead of the longest one.

Promise.all suits required parallel work and fails fast, allSettled reports every outcome for independent work, race settles with the first result and is used for timeouts, and any takes the first success for fallbacks.
Promise.all suits required parallel work and fails fast, allSettled reports every outcome for independent work, race settles with the first result and is used for timeouts, and any takes the first success for fallbacks.

Real-World Examples

  • Promises were standardized in ECMAScript 2015 after the community Promises/A+ specification unified competing libraries such as Q, when.js and Bluebird, and the fetch API, service workers and nearly every modern browser API were designed to return promises.
  • Node.js changed its default in version 15 so that unhandled promise rejections terminate the process, after years of warnings, because silently ignored rejections were hiding real failures in production servers.
Key TakeawaysA promise settles once, fulfilled or rejected, and then returns a new promise, so chains read like synchronous code with catch and finally. Wrap callback and event APIs with the constructor, but never wrap existing promises. Start work first, then choose all for required results, allSettled for independent ones, race for timeouts and any for fallbacks, and handle every rejection.

Review Questions & Answers

then returns a new promise that resolves with whatever the handler returns, waits if the handler returns a promise, and rejects if the handler throws. Each step therefore feeds the next, and a single catch at the end handles errors from any earlier step.

When the operations are independent and partial success is useful, such as dashboard widgets or batch uploads. Promise.all rejects as soon as one fails and discards the other results, which suits only operations that are all required.

Wrapping code that already returns a promise inside new Promise and manually calling resolve and reject. It adds needless code and often loses errors thrown in the inner promise. Returning or chaining the existing promise is simpler and correct.

Each request only starts after the previous one finishes, so the total time is the sum of all durations. Starting all requests first and awaiting them together with Promise.all or allSettled runs them concurrently, so the total time is roughly the longest single request.