Coding

JavaScript Promise Explained: States, then/catch and Chaining

A JavaScript promise is an object that stands for a result that isn't ready yet: it starts pending, then becomes either fulfilled with a value or rejected with an error, exactly once. You attach code to run at that moment with .then() for success and .catch() for failure, or wait for it with await.

fetch("/api/user")                 // returns a promise immediately
  .then(response => response.json())
  .then(user => console.log(user.name))
  .catch(err => console.error("Failed:", err));

The examples below were run in Node.js 18.18 and the outputs shown are from that run.

The three states of a promise

StateMeaningHandler that runs
pendinginitial state, neither fulfilled nor rejectednone yet
fulfilledthe operation completed successfully; the promise holds a value.then(onFulfilled)
rejectedthe operation failed; the promise holds a reason (usually an Error).catch() or .then(_, onRejected)

A promise that is fulfilled or rejected is called settled. Once settled it never changes: the value or reason is stored, and any handler you attach later, even minutes later, gets that same stored result.

Why promises exist: callbacks

Before promises, each asynchronous step took a callback, and a sequence of steps nested one inside another. MDN's guide calls this the "pyramid of doom":

doSomething(function (result) {
  doSomethingElse(result, function (newResult) {
    doThirdThing(newResult, function (finalResult) {
      console.log(`Got the final result: ${finalResult}`);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

With promises the same sequence is flat, and one .catch() at the end handles a failure at any step, including an exception thrown by your own code:

doSomething()
  .then(result => doSomethingElse(result))
  .then(newResult => doThirdThing(newResult))
  .then(finalResult => console.log(`Got the final result: ${finalResult}`))
  .catch(failureCallback);

How to create a promise with new Promise

Most of the time you consume promises that APIs give you (fetch, fs/promises, database drivers). You create one yourself mainly to wrap an older callback-style API. The constructor takes an executor function with two arguments, resolve and reject:

function wait(ms, value) {
  return new Promise((resolve, reject) => {
    if (ms < 0) return reject(new Error("ms must be >= 0"));
    setTimeout(() => resolve(value), ms);
  });
}

wait(500, "done").then(v => console.log(v));   // "done" after 0.5 s

Three rules from MDN's constructor reference that explain a lot of puzzling behaviour:

  • The executor runs synchronously, as soon as the promise is constructed. Only the handlers run later.
  • Only the first call to resolve or reject counts. Later calls are ignored.
  • If the executor throws before calling either, the promise rejects with that error.
const p = new Promise(resolve => {
  console.log("executor runs now");
  resolve("first");
  resolve("second");          // ignored
});
console.log("after constructor");
p.then(v => console.log("then got", v));

Output:

executor runs now
after constructor
then got first

How then, catch and finally chain

Every call to .then(), .catch() or .finally() returns a new promise. What your handler returns decides what that new promise does:

  • return a plain value: the next promise fulfills with it;
  • return a promise: the next step waits for it and takes its result;
  • throw: the next promise rejects, and the chain skips forward to the nearest .catch().
Promise.resolve(1)
  .then(x => x + 1)
  .then(x => { throw new Error("step 3 failed at " + x); })
  .then(() => console.log("skipped"))
  .catch(e => console.log("catch:", e.message))
  .finally(() => console.log("finally runs"));

Output:

catch: step 3 failed at 2
finally runs

"skipped" never prints, because a rejection jumps over every .then() success handler until something catches it. .finally() runs whether the promise fulfilled or rejected, which makes it the place for clean-up such as hiding a loading spinner. A .catch() that returns normally turns the chain back into a success, so later .then() calls run again.

The most common mistake: forgetting to return

If a handler starts another promise but does not return it, the chain cannot wait for it. MDN calls this a "floating" promise:

// wrong: result is undefined, and a fetch error goes unhandled
getUrl()
  .then(url => { fetch(url); })
  .then(result => console.log(result));

// right
getUrl()
  .then(url => fetch(url))          // arrow with no braces returns implicitly
  .then(result => console.log(result.status));

Arrow functions without braces return their expression automatically. Once you add { }, you need an explicit return.

Running promises together: all, allSettled, any, race

Four static methods take an array of promises and return one promise. Results from the test run, using the wait helper above:

await Promise.all([wait(50, 1), Promise.reject(new Error("first fail"))]);
// rejects: first fail

await Promise.allSettled([Promise.resolve(1), Promise.reject(new Error("no"))]);
// [{status:"fulfilled",value:1},{status:"rejected",reason:Error: no}]

await Promise.any([Promise.reject(new Error("x")), wait(20, "fast")]);
// "fast"

await Promise.any([Promise.reject(new Error("x")), Promise.reject(new Error("y"))]);
// rejects: AggregateError "All promises were rejected", with .errors.length 2

await Promise.race([wait(100, "slow"), wait(10, "quick")]);
// "quick"
UseWhen you want
Promise.allevery result, and to fail fast if any one fails
Promise.allSettledevery outcome, successes and failures, without failing early
Promise.anythe first success, ignoring failures unless all fail
Promise.racewhichever settles first, success or failure (for example, a timeout)

MDN also documents newer helpers, Promise.withResolvers() and Promise.try(). They are not available in every runtime yet: in the Node.js 18.18 test run, typeof Promise.withResolvers and typeof Promise.try both printed undefined. Check support before relying on them.

When do promise handlers run?

Never synchronously. Even for a promise that is already fulfilled, .then() callbacks are queued as microtasks, which run after the current code finishes but before timers such as setTimeout(fn, 0):

setTimeout(() => console.log("timeout 0"), 0);
Promise.resolve().then(() => console.log("microtask"));
console.log("sync end");

Output:

sync end
microtask
timeout 0

Unhandled rejections

A rejected promise with no .catch() anywhere is an unhandled rejection. Since Node.js 15 the default mode is throw: Node emits the unhandledRejection event and, if nothing listens for it, treats the rejection as an uncaught exception. Running a file containing only Promise.reject(new Error("nobody caught me")) printed the error with its stack trace and exited with code 1. Browsers do not stop the page; they fire an unhandledrejection event on window, and if nothing calls preventDefault() on it, an error message ends up in the console. The fix in both cases is to end every chain with .catch(), or to await the promise inside try/catch.

Promises with async/await

await is the other way to consume a promise: it pauses an async function until the promise settles and hands you the value, or throws the reason. The first chain in this article becomes:

async function showUser() {
  try {
    const response = await fetch("/api/user");
    const user = await response.json();
    console.log(user.name);
  } catch (err) {
    console.error("Failed:", err);
  }
}

JavaScript async/await explained covers the details, including sequential vs parallel awaits and the forEach trap.

Frequently asked questions

What is the difference between resolved and fulfilled?
Fulfilled is a state: the operation succeeded and the promise has a value. Resolved means the promise's fate is locked in, either because it settled or because it was resolved with another promise and now follows that one. A resolved promise can therefore still be pending, or end up rejected. In everyday speech people often use resolved to mean fulfilled.
Can a promise be cancelled?
No. A standard JavaScript promise has no cancel method; once the work has started, the promise will eventually settle or stay pending. To stop the underlying operation, use the API's own mechanism, such as passing an AbortController's signal to fetch and calling abort(), which MDN documents as able to abort fetch requests.
Does a promise run its code more than once?
No. The executor function passed to new Promise runs exactly once, when the promise is created. Every .then() attached afterwards receives the same stored result, so attaching three handlers does not repeat the work three times.
Should I use promises or async/await?
Both. async/await is syntax on top of promises: an async function returns a promise, and await unwraps one. Use await for step-by-step logic and Promise.all, Promise.allSettled and similar methods to run independent work together.

Sources