Promises

Intermediate · 12 min

The `Promise` object standing in for a value that doesn't exist yet — its three states, chaining with `.then`/`.catch`/`.finally`, and ways to combine promises.

Before thisCallbacks and Callback Hell

Web Dev Simplified · 12 min

Promises

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev SimplifiedReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A `Promise` is an object that stands in for a value that doesn't exist yet — a placeholder you can attach behavior to *now*, even though the actual result only arrives later.
  • A promise has exactly one of three states: pending (not settled yet), fulfilled (succeeded, with a value), or rejected (failed, with a reason). Once it leaves pending, it's settled permanently — it can never change state again.
  • `.then(onFulfilled, onRejected)` registers what runs once the promise settles; `.catch(onRejected)` is shorthand for a `.then()` with only the rejection handler; `.finally()` runs regardless of whether the promise fulfilled or rejected.
  • Every `.then()` returns a *new* promise, which is what makes chaining work — `somePromise.then(a).then(b).then(c)` reads top to bottom instead of nesting, and a single `.catch()` at the end can handle a failure from any step in the chain.
  • Four static methods combine multiple promises at once, and they differ in when they settle and how they handle failure: `Promise.all` (fails fast on the first rejection), `Promise.allSettled` (waits for everything, never short-circuits), `Promise.race` (settles with whichever promise finishes first, success or failure), and `Promise.any` (settles with the first *success*, rejecting only if every one fails).

A value that doesn’t exist yet, but that you can still hold

Callback hell came from a real constraint: a callback’s result only exists inside that callback, so anything depending on it has to live there too. A Promise breaks that constraint by giving the eventual result its own object, right now, before the underlying work has even finished. You can store a promise in a variable, return it from a function, pass it around — all before anyone knows whether the operation it represents will succeed or fail. The waiting and the reacting become separate things, which is exactly what lets chains stop nesting.

Three states, and only one direction

Every promise starts pending. From there it moves to exactly one of two final states: fulfilled, with a value, or rejected, with a reason (usually an Error). Once it reaches either of those, it’s settled — permanently. A promise can’t fulfill and then later reject, or vice versa; whatever happened, happened once.

const promise = fetch("/api/user");
// pending the instant it's created, before any response has arrived

Reacting to a promise: .then, .catch, .finally

.then(onFulfilled, onRejected) is how you attach behavior for when the promise settles. In practice, the rejection handler is almost always split off into its own .catch() instead — .catch(fn) is just shorthand for .then(undefined, fn), read more clearly:

fetch("/api/user")
  .then((response) => response.json())
  .then((user) => console.log(user))
  .catch((error) => console.error("Failed:", error))
  .finally(() => console.log("Request finished, one way or another"));

.finally() runs no matter which way the promise settled — it doesn’t receive the value or the error, which is the signal that it’s meant for cleanup (hiding a spinner, closing a connection) rather than for handling the result itself.

The chaining here isn’t a trick — it’s a direct consequence of .then() always returning a brand-new promise. That new promise settles based on whatever the handler you passed in returns (or throws), which is exactly what the next .then() in the chain attaches to. That’s how a chain of dependent async steps reads top-to-bottom instead of drifting right with every step, and how one .catch() at the end can catch a failure thrown from any earlier link in the chain, instead of needing a separate check at each one. The embedded video walks through defining and consuming a promise this way from scratch, which is worth watching closely if the mechanics of “a .then() handler’s return value becomes the next promise’s value” don’t click from the code alone.

When you have more than one promise at once

Chaining handles “do this, then that.” Plenty of real situations need several independent promises handled together instead — and JavaScript gives you four static methods, each with a different rule for when it settles and how it treats failure.

Method Settles when On failure
Promise.all every input fulfills rejects immediately on the first rejection
Promise.allSettled every input settles, fulfilled or rejected never rejects — gives a {status, value/reason} per item
Promise.race the first input settles, either way can resolve or reject, whichever happens first
Promise.any the first input fulfills rejects only if every input rejects (AggregateError)
// All three must succeed, or we want to know immediately that one failed
const [user, orders, prefs] = await Promise.all([
  fetchUser(), fetchOrders(), fetchPreferences(),
]);

// We want every result, successes and failures alike, with nothing discarded
const results = await Promise.allSettled([fetchA(), fetchB(), fetchC()]);

// Whichever mirror responds first wins — success or failure
const fastest = await Promise.race([mirror1(), mirror2(), mirror3()]);

// We just need one working mirror; a slow or failing one shouldn't matter
const firstWorking = await Promise.any([mirror1(), mirror2(), mirror3()]);

Promise.all and Promise.race are the older two, standard since 2015; allSettled and any filled in the gaps — “wait for everything regardless of failure” and “first success wins” — once real usage showed those were common needs all and race didn’t cover on their own.

Where this fits

This builds directly on callbacks and callback hell — promises exist specifically to fix the nesting and scattered error handling that lesson walked through. From here, async/await is syntax sugar built directly on top of everything here: await is just a different way to write “wait for this promise, then continue,” and the states, chaining, and combinators from this lesson are exactly what it’s sugar over.

Check yourself

  1. 01What problem does a `Promise` actually solve, compared to the plain callback pattern from the previous lesson?

    A promise turns "the result of this async operation" into a real value you can hold, pass around, and attach behavior to — instead of only being able to react to a result from inside a callback that someone else calls for you. That's what lets chains flatten instead of nest, and what lets one `.catch()` cover a failure from any step instead of repeating error checks by hand at every level.

  2. 02A promise just rejected. Can it later fulfill instead, if the underlying operation eventually succeeds?

    No. Once a promise leaves the pending state, it's settled permanently — whichever state it reached, fulfilled or rejected, is final. If you need a fresh attempt, you need a brand-new promise, not the same one changing its mind.

  3. 03Why does chaining `.then().then().then()` work instead of nesting one `.then()` inside another?

    Every call to `.then()` returns a new promise — one that settles based on whatever the handler you passed to it returns (or throws). That returned promise is exactly what the next `.then()` in the chain is attached to, so each step can be written one after another instead of inside the one before it.

  4. 04You need to fetch data from three independent APIs and only care about the result once *all three* have succeeded — and you want to bail out the moment any one of them fails. Which combinator fits, and which one would be wrong here?

    `Promise.all` fits: it resolves once every input promise has fulfilled, and rejects immediately as soon as any one of them rejects, with the other results simply discarded. `Promise.allSettled` would be the wrong pick for this case — it waits for every promise no matter what and never rejects, so it wouldn't give you the "bail out on the first failure" behavior you want.

  5. 05What's the actual difference between `Promise.race` and `Promise.any`, since both sound like "first one wins"?

    `Promise.race` settles with whichever promise finishes *first*, regardless of whether that one succeeded or failed — a fast failure still wins the race. `Promise.any` specifically waits for the first *success*; a fast failure is ignored and `Promise.any` keeps waiting, only rejecting (with an `AggregateError`) if every single input promise ends up failing.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark