Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 156 ยท Asynchronous JavaScript

Promises

Learn what a JavaScript promise is, create your own with new Promise, consume results with then, catch and finally, and chain async steps cleanly.

A promise is an object that stands for a value you don't have yet. When you order food at a counter, you get a receipt with a number on it. The receipt isn't your meal, but it's a promise that you'll get one, or be told that something went wrong. You can hold on to it, hand it to a friend, and decide in advance what to do when your number is called.

Promises are the foundation of modern asynchronous JavaScript. fetch() returns one, so do most new browser and Node.js APIs, and async/await is built entirely on top of them. They fix the problems you met in Asynchronous Callbacks: no more pyramids, one place to handle errors, and results that arrive exactly once. In this lesson you'll consume promises, create your own and chain them together.

The three states

Every promise is in one of three states:

  • pending: the work isn't finished yet. Every promise starts here.
  • fulfilled: the work succeeded, and the promise holds a value.
  • rejected: the work failed, and the promise holds a reason, usually an Error.

A promise that is fulfilled or rejected is called settled. Settling happens once: after that, the state and the value never change. That single guarantee removes a whole class of "callback called twice" bugs.

Consuming a promise: then, catch and finally

You don't read a promise's value directly. Instead you register callbacks for when it settles:

  • .then(onFulfilled) runs when the promise is fulfilled, and receives the value.
  • .catch(onRejected) runs when it's rejected, and receives the reason.
  • .finally(onSettled) runs either way, with no argument, which makes it ideal for clean-up.

Promise.resolve(value) and Promise.reject(reason) create promises that are already settled, which is handy for experimenting:

JS then, catch and finally

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that "Callbacks registered" prints first, even though both promises were already settled. Promise callbacks are always asynchronous: they run as microtasks, after the current code finishes. As you learned in How Asynchronous JavaScript Works, that makes promise code predictable, never "sometimes sync, sometimes async".

Creating a promise

To wrap your own asynchronous work in a promise, use the Promise constructor. You give it a function, called the executor, which receives two functions: resolve to fulfill the promise and reject to reject it.

JavaScript
const promise = new Promise((resolve, reject) => {
  // start some work...
  // later, call resolve(value) on success
  // or reject(new Error("...")) on failure
});

The most famous small example turns setTimeout into a promise-based wait():

JS Making a promise-based wait()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Run it several times; about one roll in six fails. Some rules about the executor:

  • It runs immediately and synchronously, when new Promise(...) is called. Only resolve/reject are delayed.
  • Only the first call to resolve or reject counts. Later calls are ignored.
  • If the executor throws, the promise is rejected with that error.
  • Always reject with an Error object, for the same reasons as in Throwing and Custom Errors.

Turning callback APIs into promises

The constructor's main job is wrapping old callback-style functions. Here is the error-first checkStock from the callbacks lesson, "promisified":

JavaScript
function checkStockAsync(item) {
  return new Promise((resolve, reject) => {
    checkStock(item, (error, count) => {
      if (error) reject(error);
      else resolve(count);
    });
  });
}

checkStockAsync("apple").then((count) => console.log(count));

Node.js even ships a helper for this, util.promisify(). In everyday code you'll mostly consume promises from APIs like fetch() and write new Promise only at these boundaries.

Chaining

Here's the feature that makes promises so much better than callbacks: .then() returns a new promise. That new promise settles with whatever your callback returns, so you can chain steps one after another:

  • Return a plain value, and the next .then receives it.
  • Return a promise, and the chain waits for it, then passes on its value.
  • Throw an error (or return a rejected promise), and the chain skips ahead to the next .catch.
JS A flat chain instead of a pyramid

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This is the same four-step job that formed a pyramid in the callbacks lesson. Now it reads top to bottom, and a single .catch at the end handles a failure in any step. Try changing total: 42.5 to total: 420 and run it again: step 4 is skipped and the catch reports the problem.

Recovering from errors

.catch() also returns a promise. If your catch callback returns a value instead of throwing, the chain is back on the happy path, so later .then callbacks run with that value. Where you place .catch decides what it covers:

JS Catch, recover and continue

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Because showProfile returns its chain, the caller can wait for it and run the next profile afterwards. Returning promises from functions is what lets you build bigger flows from small pieces.

Microtask timing, step by step

Each .then callback is queued as a microtask only once the promise before it settles. Run this and predict the order first:

JS Promise callbacks are microtasks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The executor is synchronous, so 2 prints straight away. When the script ends, the microtask queue holds the first .then and the queueMicrotask callback. The second .then is only queued after the first one runs, so it lands behind 5. The timer, a regular task, comes last.

Common mistakes

Forgetting to return. If a .then callback starts async work but doesn't return its promise, the chain doesn't wait for it, and its errors escape the .catch:

JavaScript
// Wrong: the next step runs immediately with undefined
getUser(1)
  .then((user) => { getOrders(user); })
  .then((orders) => console.log(orders)); // undefined

// Right
getUser(1)
  .then((user) => getOrders(user))
  .then((orders) => console.log(orders));

Nesting instead of chaining. Putting .then inside .then rebuilds the pyramid. Return the inner promise and continue the chain at the outer level.

Wrapping a promise in a new promise. If a function already returns a promise, just return or chain it. new Promise((resolve) => fetchThing().then(resolve)) adds noise and silently loses rejections.

Leaving rejections unhandled. A rejected promise with no .catch produces an "Uncaught (in promise)" error in the console, and in Node.js it can stop the whole process. Every chain should end with a .catch somewhere, or be returned to a caller who handles it:

JS An unhandled rejection

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Inspecting promises. Browser DevTools show a promise's state and value when you log it, like Promise {<fulfilled>: 3}. The console in these editors prints Promise { โ€ฆ } instead, so log the value inside .then() when you want to see it.

Promise.withResolvers()

Sometimes the code that settles a promise lives outside the executor, for example in an event handler. Promise.withResolvers() returns the promise together with its resolve and reject functions:

JavaScript
const { promise, resolve, reject } = Promise.withResolvers();

button.addEventListener("click", () => resolve("clicked!"), { once: true });
promise.then((message) => console.log(message));

It's part of ES2024 and has worked in all major browsers since early 2024 (Chrome and Edge 119, Firefox 121, Safari 17.4) and in Node.js 22+. In older environments, create the promise with the constructor and copy resolve into an outer variable.

When you need to run several promises at once, the combinators Promise.all(), allSettled(), race() and any() take over; they have their own lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A promise has been fulfilled with the value 5. Then the code calls reject(new Error("late")). What is its state now?

    Once settled, a promise never changes. Later calls to resolve or reject are ignored.
  2. 2. When does the executor function passed to new Promise(...) run?

    The executor runs right away. Only the then/catch/finally callbacks are deferred.
  3. 3. Inside a .then callback you call return getOrders(user), which returns a promise. What does the next .then receive?

    Returning a promise from then makes the chain wait for it and pass along its fulfilled value.
  4. 4. In a().then(b).then(c).catch(d), step b throws an error. What runs next?

    A thrown error rejects the chain, which skips the remaining then callbacks and jumps to the next catch.
  5. 5. What does this log, in order? Promise.resolve().then(() => console.log("A")); console.log("B");

    Promise callbacks are always asynchronous microtasks, so the synchronous B prints first.

Summary

  • A promise represents a future value and is pending, fulfilled or rejected; it settles exactly once.
  • .then() handles the value, .catch() the error, .finally() clean-up; their callbacks always run asynchronously as microtasks.
  • new Promise((resolve, reject) => โ€ฆ) wraps async work; the executor runs synchronously. Use it mainly to promisify callback APIs.
  • .then() returns a new promise, so steps chain flatly; return values and promises pass down the chain.
  • A thrown error skips to the next .catch(), which can recover by returning a value.
  • Always return promises from .then callbacks and functions, and never leave a rejection unhandled.

Next: async and await โ€” write promise-based code that reads like ordinary, step-by-step code.