Skip to content

How do JavaScript promises work?

Updated Nov 30, 20263 min readBased on official documentation
How do JavaScript promises work?

In short

A JavaScript promise is an object that stands for a result that is not ready yet, such as data from a network request. You attach callbacks to it with then and catch, and they run when the work finishes or fails. Promises chain together, so several asynchronous steps can read top to bottom instead of nesting.

What a promise represents

Some work in JavaScript takes time. Fetching data from a server is a common example. A promise is an object that stands in for the result of that work. At the moment you receive it, the result may not exist yet. Later the promise settles, either fulfilled with a value or rejected with an error.

Because the promise is an object, you can pass it around, store it, and decide later what to do with its outcome. You do not need to hand a callback into the function that starts the work.

How chaining works

Before promises, running several asynchronous steps in a row meant nesting callbacks inside callbacks. This pattern is often called callback hell, or the pyramid of doom. Each step sat one level deeper than the last, which made code hard to read and error handling hard to get right.

Promises fix this with chaining. The key detail is that the then method returns a new promise, not the original one. That new promise tracks the completion of the callback you passed in. If that callback returns another promise, the chain waits for it before moving on.

A flat chain looks like this:

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

Each then handler receives the value that the previous step produced. The arguments to then are optional, and catch is a shorthand for then with only a failure handler.

Always return promises from handlers

The most common mistake with chains is forgetting to return a promise from a then handler. Suppose a handler starts a fetch but does not return it:

doSomething()
  .then((url) => {
    fetch(url);
  })
  .then((result) => {
    // result is undefined here
  });

The next handler runs right away, without waiting for the request. Its value is undefined, and nothing can track the request anymore. Such a promise is called floating. The fix is to return it, so the chain waits for it to settle and passes its value along.

This matters even more when the code reads shared state. A floating promise can cause a race condition, where a later step reads data before it is complete. As a rule of thumb, when a handler starts a promise, return it.

Error handling

Errors travel down the chain until a catch handler picks them up. A single catch at the end covers every step above it. This is similar to how a try block works in synchronous code. Promises also catch thrown exceptions inside handlers, so one final catch handles both rejected promises and unexpected errors.

If you need some steps to fail quietly while others must succeed, you can nest a small chain with its own catch. The nested catch handles only the optional part, and the outer catch still handles failures in the critical steps. Keep chains flat when you do not need this kind of precision.

Async and await

The async and await keywords let you write promise code that looks like ordinary synchronous code. An await expression pauses only the async function it lives in, while the rest of the program keeps running. The error handling uses a normal try and catch block.

Async and await are built on promises, so the same functions work with both styles. Many developers use async and await for readability and keep plain chains for simple transformations. One drawback is that it is easy to forget the await keyword, because the code then silently works with a promise object instead of its value.

Common mistakes

Beyond missing return statements, watch for these habits. Do not nest chains by default, since a flat chain is easier to follow. Do not ignore the final catch, because an unhandled rejection can hide real problems. Do not mix callbacks and promises in the same flow, since that makes it unclear which path handles an error.

If you are new to asynchronous code in general, read about the event loop first, since it explains when your callbacks actually run.

FAQ

Is a promise the same as an async function?

No. A promise is an object that represents a future result. An async function is a function that always returns a promise and lets you use await inside it.

Why does my then handler receive undefined?

The previous handler probably started a promise without returning it. Add a return keyword in front of that promise so the chain waits for it.

Do I need try and catch with promises?

Usually not. Promises route errors to the nearest catch handler down the chain. With async and await, a try and catch block works as expected.

Can a promise resolve more than once?

No. Once a promise settles, either fulfilled or rejected, its state does not change again.

Sources

This page is based on the official documentation below. Read it for full detail.

Promises — official documentation ↗
blozhikDeveloper news from across the web, explained. Every story links to its original sources.