Chaining, and Where Errors Go
Each then returns a new promise, which is what makes chains work, and understanding that one fact explains every error-handling rule.
then returns a new promise carrying whatever the callback returned. A returned promise is waited for rather than nested. A rejection skips every then until it finds a catch, and a catch that returns a value puts the chain back on the fulfilled path.
EXERCISE
1then Returns a New Promise
Chains are not a special feature. They fall out of one method returning the same kind of thing it was called on.
The fact everything else follows from:
const p1 = Promise.resolve(1);
const p2 = p1.then((n) => n + 1);
console.log(p1 === p2); // false
console.log(p2 instanceof Promise); // true
p2.then((n) => console.log(n)); // 2
.then did not modify p1. It created a new promise that will be fulfilled with whatever the callback returned.
Which is why chains work at all:
Promise.resolve(2)
.then((n) => n * 3)
.then((n) => n + 1)
.then((n) => console.log(n)); // 7
Each link takes the previous value, returns something, and that return value becomes the next link's input. There are four promises here, not one.
A returned promise is waited for, not nested:
Promise.resolve("/api/user")
.then((url) => fetch(url)) // returns a promise
.then((response) => response.json()) // also returns a promise
.then((user) => console.log(user.name));
If a callback returns a promise, the chain pauses until that promise settles and passes on its value, not the promise itself. You never get Promise { Promise { ... } }. This flattening is the single biggest improvement over nested callbacks, and it is why the pyramid of doom does not reappear here.
Forgetting to return is the classic chain bug:
// Broken: nothing returned, so the next link gets undefined
Promise.resolve("/api/user")
.then((url) => {
fetch(url);
})
.then((response) => {
console.log(response); // undefined
});
// Fixed
Promise.resolve("/api/user")
.then((url) => {
return fetch(url);
})
.then((response) => {
console.log(response.status);
});
This is the arrow-function brace trap from Unit 5 of the beginners course, met again in a place where it does real damage: the chain carries on with undefined and the failure surfaces one link later.
And a non-promise return is wrapped for you:
Promise.resolve(1)
.then((n) => n + 1) // returns 2, a plain number
.then((n) => console.log(n)); // 2
You do not have to return a promise. Anything you return becomes the fulfilment value of the next one.
Read a chain as a pipeline of transformations rather than as a sequence of steps. Each .then is "given the previous value, produce the next one", which makes the missing-return bug obvious: a link that produces nothing hands undefined to whatever comes after it.
EXERCISE
2Where a Rejection Goes
An error does not stop at the next line. It skips forward until something is willing to handle it.
A rejection skips every then until it finds a catch:
Promise.reject(new Error("failed"))
.then(() => console.log("A")) // skipped
.then(() => console.log("B")) // skipped
.catch((err) => console.log("caught:", err.message))
.then(() => console.log("C")); // runs
// caught: failed
// C
Two things there are worth separating. The rejection skipped both then callbacks, and after the catch the chain continued normally. C ran.
Because catch returns a promise too, and a normal return fulfils it:
Promise.reject(new Error("failed"))
.catch((err) => {
console.log("handling");
return "recovered";
})
.then((value) => {
console.log(value); // recovered
});
A catch that returns a value puts the chain back on the fulfilled path. That is how you supply a fallback. If you want the failure to keep travelling, re-throw:
Promise.reject(new Error("failed"))
.catch((err) => {
console.log("logging it");
throw err; // still rejected after this
})
.then(() => console.log("not reached"))
.catch((err) => console.log("caught again:", err.message));
A throw anywhere in a chain becomes a rejection:
Promise.resolve("data")
.then((value) => {
throw new Error("processing failed");
})
.catch((err) => console.log(err.message)); // processing failed
You do not need a try block inside a .then. Throwing is the way to reject from inside a chain.
Position matters, and one placement is almost always wrong:
// A catch in the middle only covers what came before it:
fetchUser()
.catch(() => null) // covers fetchUser only
.then((user) => user.name); // TypeError here is NOT caught
// A catch at the end covers the whole chain:
fetchUser()
.then((user) => user.name)
.catch((err) => console.log("something failed:", err.message));
And finally runs either way, passing the result through untouched:
showSpinner();
fetchUser()
.then((user) => render(user))
.catch((err) => showError(err))
.finally(() => hideSpinner());
finally receives no argument and its return value is ignored, which is exactly right for cleanup: it cannot accidentally change the outcome.
Pro Tip: One
catchat the end of a chain, andfinallyafter it for cleanup. Reach for a mid-chaincatchonly when you genuinely mean "recover from this specific step and continue", and when you do, make the recovery value obviously a fallback so the next reader can see what happened.
EXERCISE
3How a Chain Runs Over Time
Each link in a chain is a separate microtask, which makes chain timing predictable by Unit 4's rule.
Chains do not run all at once. Every .then callback is queued as its own microtask, and that explains ordering that otherwise looks arbitrary.
Two chains interleave, link by link:
Promise.resolve()
.then(() => console.log("A1"))
.then(() => console.log("A2"))
.then(() => console.log("A3"));
Promise.resolve()
.then(() => console.log("B1"))
.then(() => console.log("B2"))
.then(() => console.log("B3"));
// A1
// B1
// A2
// B2
// A3
// B3
Not A1 A2 A3 B1 B2 B3. Only A1 and B1 were queued at the start. A2 was queued when A1 finished, by which time B1 was already waiting. The queues alternate because each chain adds one link at a time.
Returning a promise costs extra turns:
Promise.resolve()
.then(() => console.log("1"))
.then(() => console.log("2"));
Promise.resolve()
.then(() => Promise.resolve()) // returning a promise
.then(() => console.log("3"));
// 1
// 2
// 3
3 lands after 2 even though its chain is shorter. Resolving a returned promise takes two additional microtask turns, because the runtime has to call .then on it and then wait for that to settle. It is a real detail rather than trivia: it is why return await x inside a chain is measurably different from return x.
And this is why a chain never shows half-finished state:
setStatus("loading");
fetchUser()
.then((user) => setName(user.name))
.then(() => setStatus("ready"));
// The browser cannot paint between setName and setStatus, because
// both are microtasks and rendering happens after the queue drains.
That guarantee, from Unit 4, is the practical payoff of promise callbacks being microtasks rather than macrotasks. A user never sees the name updated while the status still says loading.
A useful debugging technique that follows from it:
fetchUser()
.then((user) => {
console.log("1. got user", user.id);
return fetchPosts(user.id);
})
.then((posts) => {
console.log("2. got posts", posts.length);
return posts;
})
.catch((err) => {
console.log("failed at whichever step logged last");
throw err;
});
Numbering the links tells you exactly where a chain stopped, which a stack often will not, because by the time a rejection surfaces the original call stack is long gone.
