AI Hints
JavaScript · Lesson 83 of 138

then and catch

Using promises.

⏱ 2 min read▶ Video at 1:40:15🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

then and catch
From the video: then and catch
  • 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.

app.jsjavascript
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"));
Output
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(...)
Next up: async and await — async code that reads easily