then and catch
Using promises.
You rarely make promises yourself. Usually a function gives you one, and you decide what to do when it settles. Then handles success, catch handles errors, and you can chain them in a flat line.

- Functions give you promises
- then for success
- catch for errors
A flat chain
Each then receives the value from the step before, and whatever it returns goes to the next then. If it returns a promise, the chain waits for it. One catch at the end handles an error from any step. And finally runs either way. Run it.
const wait = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
wait(100, 1)
.then(a => { console.log("Step one:", a); return wait(100, a + 1); })
.then(b => { console.log("Step two:", b); return b * 10; })
.then(c => { console.log("Step three:", c); throw new Error("Oops"); })
.catch(err => console.log("Caught:", err.message))
.finally(() => console.log("Chain finished"));Step one: 1 Step two: 2 Step three: 20 Caught: Oops Chain finished
Callbacks and promises
Compare this with the pyramid from before. The promise chain is flat, it reads from top to bottom, and there's one place for errors. That's why every modern browser and Node feature that takes time returns a promise.
Callbacks
- Nested deeper each step
- Errors at every level
- Hard to read
Promises
- A flat chain
- One catch
- Top to bottom
Summary
Then handles each value, returning a promise makes the chain wait, and one catch handles any error. Next, async and await, the nicest way to use promises.
Key takeaways- .then(value => ...)
- .catch(err => ...)
- .finally(...)