链中多次拒绝呼叫被捕获

时间:2019-07-13 07:41:01

标签: javascript es6-promise

我一直在尝试Promise和错误处理,但是我无法解释一段代码的行为。 Promise.reject被调用了两次,第一个被完美地处理,但后者根本没有被嘲笑。

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
  });



我希望catch能够捕获第14行(Promise.reject('promise reject 2'))中引入的错误,但是从来没有调用catch处理程序

1 个答案:

答案 0 :(得分:1)

Promise.reject()仅使一个被拒绝的Promise对象。您的连锁店对此一无所知,除非您将其退回。如果返回,则下一个catch将捕获它:

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!
    }) 

您也可以在throwthen()

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!
    })