admin管理员组

文章数量:1410730

I want the third "then" to not be executed when the second "then" is called. However, it still calls the third "then" even though the promise is rejected (the second "then" is called) and the code returns "rejected" and then "undefined". How to not run the third "then" so the "undefined" won't show up?

var FirstPromise = function() {

  let promiseme = new Promise(function(res, rej) {

    if ('a' == 'b') {
      res(1);
    } else {
      rej('rejected');
    }
  })

  return promiseme;
};

function succeddcallback(msg) {
  return msg * 2;
}

function errorcallback(msg) {
  console.log(msg);
}

FirstPromise()
  .then(succeddcallback, null)
  .then(null, errorcallback)
  .then(function(succedded) {
    console.log(succedded);
  }, function(failed) {
    console.log(failed);
  })

I want the third "then" to not be executed when the second "then" is called. However, it still calls the third "then" even though the promise is rejected (the second "then" is called) and the code returns "rejected" and then "undefined". How to not run the third "then" so the "undefined" won't show up?

var FirstPromise = function() {

  let promiseme = new Promise(function(res, rej) {

    if ('a' == 'b') {
      res(1);
    } else {
      rej('rejected');
    }
  })

  return promiseme;
};

function succeddcallback(msg) {
  return msg * 2;
}

function errorcallback(msg) {
  console.log(msg);
}

FirstPromise()
  .then(succeddcallback, null)
  .then(null, errorcallback)
  .then(function(succedded) {
    console.log(succedded);
  }, function(failed) {
    console.log(failed);
  })
Share Improve this question edited Dec 11, 2017 at 14:44 Damon 4,3562 gold badges18 silver badges27 bronze badges asked Dec 11, 2017 at 14:39 januaryanandajanuaryananda 4071 gold badge6 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

That's because you caught the error in the catch statement - i.e. .then(null,errorcallback) - and you never threw another error or returned a rejected promise in it.

...which is the same as returning a resolved promise with a value of undefined, which is why your next .then executes the success callback.

If you want your error to propagate to a subsequent .catch or .then(null,fn), then your errorcallback must throw (or return a rejected promise):

function errorcallback(msg) {
  console.log(msg);
  throw new Error(msg); //or (return Promise.reject(msg);
}

Keep in mind that in every .catch (or .then(null,fn) you have to re-throw (or return a rejected promise) in order for subsequent error callbacks to get called.

本文标签: Javascript promise quotthenquot always runs even though the promise failed to executeStack Overflow