Skip to content
jshacks.dev
Async

Promise Chaining: How then Returns a New Promise

See how promise chaining works in JavaScript, why then returns a new promise, how values and errors flow down a chain and what breaks when you forget a return.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript and Vite logos.

Promise chaining is easy to use and surprisingly hard to predict until you hold one fact in your head: then never gives you back the promise you called it on. It builds and returns a second promise, and what that second promise does depends entirely on what your handler returns or throws. Once that is clear, the odd cases stop being odd, like the chain that continues after an error, the step that receives undefined and the handler that is skipped. This post works through the rules on Node.js 24 with printed output, then covers branching, the difference between a chain and several then calls on the same promise, and the two bugs that account for most chaining mistakes.

The rule

promise.then(onFulfilled, onRejected) returns a new promise, called the derived promise. Its fate is decided like this.

Handler outcomeDerived promise
Returns a plain valueFulfills with that value
Returns nothingFulfills with undefined
Returns a promise or thenableAdopts that promise's outcome
ThrowsRejects with the thrown value
Is not provided for this statePasses the original outcome through

The last row is what makes catch at the end of a chain work.

JavaScript
const original = Promise.resolve(1);
const derived = original.then((n) => n + 1);

console.log(original === derived);
console.log(await original, await derived);
Text
false
1 2

The original promise is untouched. It is still fulfilled with 1. The derived promise holds 2. Because the original never changes, you can attach many handlers to it independently, which matters in the branching section below.

Values flow down

Each handler receives what the previous one returned, so a chain is a pipeline.

JavaScript
const result = await Promise.resolve(3)
  .then((n) => n * 2)
  .then((n) => n + 1)
  .then((n) => `result: ${n}`);

console.log(result);
Text
result: 7

Three plain returns, three derived promises, one final value. Nothing here is asynchronous beyond the microtask hops, but the shape is the same when a step takes time.

Returning a promise makes the chain wait

When a handler returns a promise, the derived promise does not fulfill with the promise object. It waits and takes on the inner outcome. This is called assimilation, and it is what lets sequential asynchronous steps read flat.

JavaScript
const delay = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

const log = [];

await delay(10, "a")
  .then((value) => {
    log.push(value);
    return delay(10, "b");
  })
  .then((value) => {
    log.push(value);
    return delay(10, "c");
  })
  .then((value) => log.push(value));

console.log(log);
Text
[ 'a', 'b', 'c' ]

Each step started after the previous finished, because returning the promise made the next then wait for it. Remove one return and you break the order, which is the first of the two classic bugs.

Bug 1: the missing return

Without return, the handler gives back undefined, so the derived promise fulfills right away, and the next step runs without waiting.

JavaScript
const delay = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

await delay(10, "a")
  .then((value) => {
    delay(30, "b"); // no return
  })
  .then((value) => console.log("next step got:", value));

console.log("chain finished");
await delay(50);
Text
next step got: undefined
chain finished

The 30 ms promise was started and forgotten. The chain moved on at once, with undefined. If that inner promise rejects, nothing handles it, and Node.js reports an unhandled rejection. Arrow functions with a block body make this easy to do, because () => { fn() } returns nothing while () => fn() returns the promise.

Errors flow down too

A rejection skips every onFulfilled handler until it reaches an onRejected one. A throw inside a handler converts to a rejection.

JavaScript
Promise.resolve("start")
  .then((value) => {
    console.log("step 1:", value);
    throw new Error("broke in step 1");
  })
  .then(() => console.log("step 2 never runs"))
  .then(() => console.log("step 3 never runs"))
  .catch((error) => {
    console.log("caught:", error.message);
    return "recovered";
  })
  .then((value) => console.log("step 4:", value));
Text
step 1: start
caught: broke in step 1
step 4: recovered

The two skipped steps had no rejection handler, so the original outcome passed through them untouched. The catch returned a value, so the derived promise fulfilled and step 4 ran. If it had rethrown, step 4 would have been skipped as well.

Bug 2: nesting instead of chaining

Putting a then inside a handler works, and it brings back the pyramid.

JavaScript
const getUser = () => Promise.resolve({ id: 1 });
const getPosts = (id) => Promise.resolve([`post of ${id}`]);

getUser().then((user) => {
  getPosts(user.id).then((posts) => {
    console.log("nested:", posts);
  });
});

getUser()
  .then((user) => getPosts(user.id))
  .then((posts) => console.log("flat:", posts));
Text
nested: [ 'post of 1' ]
flat: [ 'post of 1' ]

Both print the same, but the nested version has a second problem beyond readability: it returns nothing, so an error in the inner chain is disconnected from the outer one. A catch on the outer promise would not see it. Return the inner promise and keep the chain at one level, so errors reach one catch.

When a later step needs both values, nesting is sometimes right, but await handles that better.

JavaScript
const user = await getUser();
const posts = await getPosts(user.id);
console.log(user.id, posts);
Text
1 [ 'post of 1' ]

A chain is not the same as several handlers

Calling then repeatedly on one promise creates branches, not a chain. Each branch gets the original value.

JavaScript
const base = Promise.resolve(10);

base.then((n) => console.log("branch A:", n + 1));
base.then((n) => console.log("branch B:", n * 2));

const chained = base.then((n) => n + 1).then((n) => n * 2);
console.log("chained:", await chained);
Text
branch A: 11
branch B: 20
chained: 22

Both branches received 10. The chain received 10, then 11, then produced 22. If you want sequential transformation, chain. If you want several independent consumers of one result, branch. Branches also have separate error paths, so a rejection must be handled on each branch that you want to stay quiet.

Thenables are adopted too

If a handler returns any object with a then method, the derived promise follows it. That is how promises from different libraries cooperate.

JavaScript
const thenable = {
  then(resolve) {
    resolve("from a thenable");
  },
};

console.log(await Promise.resolve().then(() => thenable));
Text
from a thenable

Thenables are covered in their own post, and they are the reason await works on objects that are not native promises.

Choosing between chaining and await

Both express the same thing. A chain is compact for a short pipeline of pure transformations. async/await is better when steps need earlier values, branch on conditions or sit inside loops. The semantics are identical, since an await is a then with the rest of the function as its handler. Learning to read a chain as a series of derived promises is what makes the awaited version easy to reason about as well.

A way to debug a chain that misbehaves

When a chain gives the wrong result, the quickest method is to add a logging step between the others that prints the value and returns it unchanged. Because every handler receives the previous return value, a step like then((value) => { console.log(value); return value; }) is invisible to the rest of the chain, and you can move it up and down until the printed value stops being what you expect. The step just before the first bad value is the one with the bug, and it is nearly always a missing return, a catch that swallowed an error or a value that was reassigned.

If the chain stalls and never produces a value, look for a promise that never settles. That is usually a callback API wrapped in new Promise where one branch forgot to call resolve or reject. Finally, remember that a chain which looks sequential may have branches hiding in it. Two separate then calls on the same promise are siblings, and if you expected one to feed the other, the second will see the original value.

Testing a promise chain

A chain is tested by awaiting its final promise, and the useful cases are the ones where a step goes wrong. Write a test for the success path that checks the final value, and then a test for each step that can fail, using a stub that rejects, and assert that the chain rejects with the expected error and that later steps did not run. Count calls in the stubs for that. Add a test for the missing-return bug by making one step's stub return a promise that resolves late, and assert that the next step received its value and not undefined. If a branch of the chain is meant to run in the background, test that its rejection is handled, by listening for unhandledRejection during the test and failing if it fires. These tests are cheap, and they pin down the two behaviors, waiting and error flow, that chains exist to provide.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.