What is Promise Chaining?
Promise chaining is linking .then() calls so each step receives the previous step's result; it works because every .then returns a new promise that resolves with whatever its handler returns, including another promise, which is waited for automatically.
Rules of the chain
- Return a value → the next
.thenreceives it. - Return a promise → the chain waits for it, then passes on its result (this is what keeps async steps flat instead of nested).
- Throw (or return a rejected promise) → the chain skips to the next
.catch(or a.thenwith a rejection handler). .catchreturns a promise too: if it returns normally, the chain recovers and continues; if it re-throws, the error keeps propagating..finallyruns either way and passes the original result through.
The most common bug
Forgetting to return inside .then. The next step then runs immediately with undefined, and the inner promise is detached (its errors become unhandled).
Nesting vs chaining
p.then(a => getB(a).then(b => ...)) nests and brings back callback hell. Return the promise instead: p.then(getB).then(b => ...). If a later step needs an earlier value, async/await is usually clearer.
Chaining vs async/await
They are equivalent. await is easier to read for sequential logic and loops; .then chains remain handy for short transformations and in code that cannot be async.
Code example
1const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));23const result = await Promise.resolve(2)4 .then((n) => n * 10) // return a value5 .then((n) => wait(10, n + 1)) // return a promise -> the chain waits6 .then((n) => {7 if (n > 20) throw new Error(`too big: ${n}`);8 return n;9 })10 .catch((err) => {11 console.log("recovering from", err.message); // recovering from too big: 2112 return 0; // the chain continues with 013 })14 .finally(() => console.log("finally runs, value passes through"))15 .then((n) => `final value: ${n}`);16console.log(result); // final value: 01718// The classic bug: missing return19const broken = await Promise.resolve(1)20 .then((n) => {21 wait(10, n + 1); // forgot `return`22 })23 .then((n) => n);24console.log(broken); // undefined2526// Flat chain instead of nesting27const getUser = (id) => wait(5, { id, name: "Ada" });28const getPosts = (user) => wait(5, [`${user.name}'s first post`]);29console.log(await getUser(1).then(getPosts)); // ["Ada's first post"]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.