CodeBlanks Logo Icon CodeBlanks

then and catch

Learn promise chaining with .then and .catch.

Get the result with then

To obtain a Promise's result you use the then method. then(value => {...}) runs when the Promise is fulfilled and processes the incoming value. Since then itself returns a Promise, you can chain calls: the value returned by one then becomes the input of the next.

p.then(value => console.log(value));

If you want to handle errors separately you can pass a second function: then(value => {...}, err => {...}). But the more readable way is to catch errors with catch.

Catch errors with catch

To catch a rejected Promise's error you use catch. catch(err => {...}) catches errors from anywhere in the chain, so it is commonly placed at the end.

p
  .then(value => value.toUpperCase())
  .catch(err => console.error(err));

catch is actually a shortcut for then(null, err => {...}). After an error is caught, catch can return a normal value, so the chain recovers and the next then runs.

Practice Your turn: a then and catch chain

Create a Promise with new Promise((resolve, reject) => resolve("hello")). Add .then(value => console.log(value)) to log the result. Add .catch(err => console.error(err)) to catch any error.

Starter code

index.js
// Create a Promise and resolve it
// Log the result with .then, catch errors with .catch

Sample solution

index.js
new Promise((resolve, reject) => resolve("hello"))
  .then(value => console.log(value))
  .catch(err => console.error(err));

Expected output

hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: catch the error

Question
p.then(value => console.log(value))
 .____(err => console.error(err));
Answer
p.then(value => console.log(value))
 .catch(err => console.error(err));

Explanation: catch runs when a Promise is rejected.

2 When does catch run in a Promise chain?

  • When any Promise in the chain is rejected Correct answer
  • When the Promise is fulfilled
  • Only when then throws
  • In every case

Explanation: catch runs after the first rejected Promise in the chain.

3 Match each method with its job

Term Meaning
then runs on success
catch catches errors
resolve signals success

All lessons in Beginner