Skip to content
Advertisement

Why do both Promise’s then & catch callbacks get called?

I have the following code and when it’s executed, it returns both “rejected” and “success“:

// javascript promise
var promise = new Promise(function(resolve, reject){
  setTimeout(function(){reject()}, 1000)
});
promise
  .catch(function(){console.log('rejected')})
  .then(function(){console.log('success')});

Could anyone explain why success is logged?

Advertisement

Answer

The then callback gets called because the catch callback is before it, not after. The rejection has already been handled by catch. If you change the the order (i.e. (promise.then(...).catch(...))), the then callback won’t be executed.

MDN says that the .catch() method “returns a new promise resolving to the return value of the callback”. Your catch callback doesn’t return anything, so the promise is resolved with undefined value.

Advertisement