The chain rule
.then does not just attach a callback. It returns a brand-new promise whose value is whatever your callback returns. That is what makes chains flat instead of nested:
- Return a plain value, and the next
.thenreceives it. - Return a promise, and the chain waits for it, then passes its resolved value along.
That second rule is the magic: async steps line up one after another with no pyramid.
Chaining is the feature that made promises win. Real work is a sequence — fetch the user, then fetch their orders, then render — where each step needs the previous step's result. Without the chain rule you would be right back to nesting callbacks inside callbacks.
Code exercise · javascript
Run it. Each callback's return value feeds the next link. Watch 2 become 4, then 9.
Code exercise · javascript
Run it. This chain returns a PROMISE from inside a `.then` (using the `delay` helper you wrote in lesson 5-1). The chain waits for each step before starting the next.
Quiz
What does `p.then(fn)` evaluate to?
Quiz
A middle callback in a chain computes `n * 2;` but has no `return`. What does the next .then receive?
Code exercise · javascript
Your turn. Complete the chain: first step uppercases the name, second step wraps it as `Hello, NAME!`. Only fill in the two TODO callbacks.