3

How would you make a call to the next error function with promise chaining?
I thought a return inside the error function would automatically call the next error function.

//Called in a controller
dataService.saveRequest()
     .then(function result(res){
        //Logged when the service sends back a result
        console.log("finished");
     }, function error(error){
        //Logged when the service sends back an error
        //THIS DOES NOT GET CALLED
         console.log("error from controller");
     });

//INSIDE THE SERVICE
this.saveRequest = function(){
   return $http.post('rest/request/send-request', someData)
       .then(function(result){
         //Goes, as expected, into the success function in the controller
         return result.data;
       }, function(error){
          //Does NOT go into the next error function
          //I need the error function to execute in the controller
           return error;
       });

};
My Stack Overfloweth
  • 4,729
  • 4
  • 25
  • 42
gr3g
  • 2,866
  • 5
  • 28
  • 52

3 Answers3

2

I tough a return inside the error function would automatically call the next error function.

No, returning means that you recovered from error situation and next will be resolved success callback. If you return from error callback and you want to pass it to the next one in chain, you need to return rejected promise:

dataService.saveRequest()
 .then(function result(res) {
    //Logged when the service sends back a result
    console.log("finished");
 }, function error(error) {
     console.log("error from controller");
     return $q.reject('error from controller');
 });

Or instead or returning you can throw something.

dfsq
  • 191,768
  • 25
  • 236
  • 258
1

When you return a value, rather than a Promise, from a handler, it is implicitly wrapped with Promise.resolve. That applies to rejection handlers too, so your rejection handler is returning a resolved promise.

You need to throw or return a rejected Promise to propagate rejection:

return $http.post('rest/request/send-request', someData)
   .then(function(result){
     //Goes, as expected, into the success function in the controller
     return result.data;
   }, function(error){
       throw error;
   });
joews
  • 29,767
  • 10
  • 79
  • 91
1

You have to return return $q.reject(); from a promise in order for the next promise in the chain to fail too. See example plunker: http://plnkr.co/edit/porOG8qVg2GkeddzVHu3?p=preview

The reason is: Your error handler may take action to correct the error. In your error-function your dealing with the error,if not specified otherwise, it will return a new promise which is resolved. Therefore it is not reasonable to have the next promise failing by default. Think of it as try/catch.

You're catching the error and handling it - so it gets to the success handler. If you want to reject it, you have to do it by returning $q.reject();

harishr
  • 17,807
  • 9
  • 78
  • 125