Catch Errors in a JavaScript Promise Chain with Promise.prototype.catch()

InstructorMarius Schulz

Share this video with your friends

Send Tweet

The Promise.prototype.then() method accepts two callbacks as parameters, onFulfilled and onRejected:

  • If the promise is fulfilled, onFulfilled will be called.
  • If the promise is rejected, onRejected will be called.
  • If the promise never settles (that is, stays pending forever), neither one will be called.

If you want to register a handler for rejected promises only, you can use the Promise.prototype.catch() method: .catch(onRejected) behaves the same as .then(undefined, onRejected).

Nikhil
~ 2 years ago

Thanks for creating this course Maruis.

At about 2:44 the importance of returning from the Promise was mentioned. During times when it is not required to chain on the promise further can one choose not to return, or, this could lead to some unintended consequences?

Marius Schulzinstructor
~ 2 years ago

@Nikhil: In those cases where there’s no further promise chaining, you can decide not to return any value. I would still highly encourage you to always end your promise chain with an error handler, e.g. using a promiseDone() util function.

Nikhil
~ 2 years ago

Hmm, ok @Marius. Had looked for ways to end the promise chain, including looking for promiseDone() usages, however, did not find anything yet. Will continue to look further, in the meanwhile if possible, sharing a code sample on how this is done would be great.