Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript promise "then" always runs even though the promise failed to execute

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);
  })
like image 777
januaryananda Avatar asked Jan 30 '23 01:01

januaryananda


1 Answers

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.

like image 162
Adam Avatar answered May 16 '23 05:05

Adam