Promise chaining with then()
How it works
then(onFulfilled, onRejected) returns a new promise. Returning an ordinary value fulfills the new promise with it; returning a thenable makes it follow that result; throwing rejects it. Missing handlers propagate the corresponding outcome. Chaining lets each operation receive the previous result. A second argument to then handles rejection of the original promise, not exceptions thrown by that same call’s fulfillment handler.
Example 1
Promise.resolve(3).then(n => n * 2).then(n => n + 1).then(console.log);Expected output in the tested environment:
7Each reaction receives the previous result.
Example 2
Promise.resolve(1).then(() => { throw new Error("bad"); }, () => "handled").catch(e => console.log(e.message));Expected output in the tested environment:
badThe later catch handles the failure from the fulfillment handler.
Common mistake
A block-bodied arrow handler needs return to pass its result onward. Omitting return often produces undefined in the next reaction.
Practice
Chain two transformations, then insert a handler that returns a rejected promise and verify the success-only stage is skipped.
Run this practice in the documented local environment. ByteMind module and asynchronous grader support is not yet verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Promise chaining with then() — Knowledge Check
Reason about the concept and predict its behavior in the indicated environment.
What does then() return?
What happens if a fulfillment handler throws?
How should a handler pass an asynchronous operation into the chain?
For Promise chaining with then(), what is the console output of example 1 in Node.js 22.16.0?
Promise.resolve(3).then(n => n * 2).then(n => n + 1).then(console.log);For Promise chaining with then(), what is the console output of example 2 in Node.js 22.16.0?
Promise.resolve(1).then(() => { throw new Error("bad"); }, () => "handled").catch(e => console.log(e.message));