1

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
      });
Abdulaziz
  • 2,201
  • 1
  • 21
  • 35
  • Just `throw new Error(reason)` if you want to use the rejection funtion. See [chaining](http://emberjs.com/api/classes/RSVP.Promise.html#toc_chaining). – Vidul Aug 09 '15 at 12:13
  • 1
    `this function returns the model.save() promise` - that's not correct. `baseCall` returns the "result" of the success or fail functions in the `then` block - as written, both success/fail will result in a resolved value of undefined - of course, there's probably code you haven't shown, otherwise the `baseCall` function makes absolutely no sense – Jaromanda X Aug 09 '15 at 12:16
  • @Bergi there is a _huge_ question, I think there is a canonical or short one already. – Benjamin Gruenbaum Aug 09 '15 at 18:36
  • @BenjaminGruenbaum: Yeah, you're right, the question isn't the best or most concise one. I've used it in the past as a canonical dupe already because my answer contains an elongated explanation :-) Maybe we should polish it up, or use an altogether different one - just ping me about it. – Bergi Aug 09 '15 at 18:48
  • @Bergi just make a canonical? Ask the question, move your answer there and dupe vote this to that. Those are definitely worth your while rep wise and are a lot more helpful than most other questions. Other canonical candidates can just be redirected there. – Benjamin Gruenbaum Aug 09 '15 at 19:53

1 Answers1

0

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
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504