Robbe Claessens
Robbe Claessens

Reputation: 99

Calling reject multiple times in the chain not being caught

I was expermenting with promises and error handling, but I cannot explain the behaviour of a piece of code. Promise.reject is called twice, the first is handled perfectly but the latter is not being caughed at all.

const a = Promise.resolve('test');

a
  .then(item => Promise.reject('promise reject 1'))
  .then(
    (a) => {
      console.log(a); // value: test
    }, 
    (err) => {
      console.log(err); // value: promise reject 1
    }
    ).then((a) => {
      console.log('continue1'); // being called
      Promise.reject('promise reject 2') // called but not caught
    }, 
    (err) => {
      console.log(err); // never being called
    })
  .catch((err) => {
    console.log(err); // never being called
  });



I expected the catch to catch the error introduced at line 14 (Promise.reject('promise reject 2')), but the catch handler is never called

Upvotes: 0

Views: 55

Answers (1)

Mark
Mark

Reputation: 92440

Promise.reject() just makes a rejected promise object. Your chain doesn't know anything about it unless you return it. If you return it, the next catch will catch it:

const a = Promise.resolve('test');

a
  .then(item => Promise.reject('promise reject 1'))
  .then(
    (a) => {
      console.log(a); // value: test
    }, 
    (err) => {
      console.log(err); // value: promise reject 1
    }
    ).then((a) => {
      console.log('continue1'); // being called
      return Promise.reject('promise reject 2') // << ---- Return me!
    }, 
    (err) => {
      console.log(err); // never being called
    })
  .catch((err) => {
    console.log("from catch:",err); // caught!
    }) 

You can also throw in then():

const a = Promise.resolve('test');

a
  .then(item => Promise.reject('promise reject 1'))
  .then(
    a => {
      console.log(a); // value: test
    }, 
    err => {
      console.log(err); // value: promise reject 1
   })
  .then(
    a => {
      console.log('continue1'); // being called
      throw(new Error('promise reject 2'))      // <-- no return required
    }, 
    err => {
      console.log(err); // never being called
   })
  .catch(err => {
    console.log("from catch:",err.message); // caught!
    })

Upvotes: 1

Related Questions