Why is the chained callback for success promises executed on both success and failure?

122 Views Asked by At

So I have a base function that saves an Ember Data model, and runs common callback code on failure then returns the promise to the caller, so the caller can chain other callbacks on its own, but somehow, the chained callbacks from the caller are not executing as intended, the success code is being executed on failure and success, while the failure code is never executed

Here's the code for the common function:

// this function returns the model.save() promise to allow chaining of promises on the caller scope.


   function baseCall() {

      return model.save().then(function () {
        //success
      }, function (reason) {
        //failure
        if (reason.errors) {
          model.set('errors', reason.errors);
        }
      });
    }  

And here's the caller code:

baseCall().then(function(post) {
        console.log('super.success');//runs on failure AND success
      }, function() {
        console.log('super.failure');//never runs
      });
1

There are 1 best solutions below

1
On BEST ANSWER

For the same reason the following code always alerts "Hello";

try {
     model.save(); // throws Error
} catch (e) {
    if (reason.errors) {
      model.set('errors', reason.errors);
    }
}
console.log("Hello");

A promise error handler, like a synchronous catch "handles" the error. If you do not want to mark the error as handled - rethrow it:

 throw reason; // always throw proper `Error`s