最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Handling errors in multiple calls of AngularJS promises - Stack Overflow

programmeradmin2浏览0评论

I have an AngularJS service with such async API:

myService.asyncCall(['id0', 'id3', 'id2']).then(function (plexData) {   
  // handle plexData
}).catch(function (error) {   
  console.log(error); 
});

asyncCall incapsulates multiple calls of $http which handled by $q.all. Each of the $http requests can response with error and I want the errors to be handled by one catch handler. So how i can achieve multiple calls of the catch handler ?

I have an AngularJS service with such async API:

myService.asyncCall(['id0', 'id3', 'id2']).then(function (plexData) {   
  // handle plexData
}).catch(function (error) {   
  console.log(error); 
});

asyncCall incapsulates multiple calls of $http which handled by $q.all. Each of the $http requests can response with error and I want the errors to be handled by one catch handler. So how i can achieve multiple calls of the catch handler ?

Share Improve this question asked Apr 29, 2014 at 13:50 Eugene GluhotorenkoEugene Gluhotorenko 3,1642 gold badges35 silver badges52 bronze badges 6
  • 1 $q.all gets rejected when any of the promises gets rejected. What exactly are you trying to achieve ? – gkalpak Commented Apr 29, 2014 at 13:54
  • @ExpertSystem, Yes, But I want to handle each possible reject from the promises array that I pass to $q.all – Eugene Gluhotorenko Commented Apr 29, 2014 at 13:59
  • Sorry, I still don't understand what you want to achieve (that's why I asked for clarification). What exactly doyou mean by "handle each possible reject from the promises array". – gkalpak Commented Apr 29, 2014 at 14:02
  • Ok, forgot about $q.all. I want my asyncCall 1. to get array of promises, 2. has one resolve handler for each resolved promise from the array (then block from the example) 3. has one reject handler that will be called for each rejected promise. (catch block from the example). I hope now it is clear. – Eugene Gluhotorenko Commented Apr 29, 2014 at 14:16
  • I still have questions :) 1. Do you want the requests to happen in parallel, sequentially, or whatever ? 2. What do you want to happen when any of the requests fails ? Continue with the rest or abort all ? 3. I understand that you want to have two functions: 1 for handling the success of any request and one for handing the error of any request (so if 3 requests succeed, your success handler should be called 3 times). Is that correct or am I still missing the point ? – gkalpak Commented Apr 29, 2014 at 14:23
 |  Show 1 more ment

2 Answers 2

Reset to default 5

If I understood correctly (finally), this is what you are trying to achieve:

  • Input:
    1. a list of promises
    2. a callback to be called when all promises have been resolved
    3. a callback to be called each time any of the promises gets rejected

  • Behaviour:
    1. You want parallel execution (not sequential).
    2. You want all promises to be either resolved or rejected (i.e. even if one promise gets rejected, the rest should continue as usual).
    3. You want the "final" callback to be called exactly once (receiving an array of results - regardless if the respective deferred was resolved or rejected).

$q.all should be "augmented" to suit your needs, because by default:

  1. It gets immediatelly rejected as soon as any of the promises in the list gets rejected.
  2. In case of rejection it returns only the rejection reason and not a list of results.

Here is a possible implementation:

function asyncCall(listOfPromises, onErrorCallback, finalCallback) {

  listOfPromises  = listOfPromises  || [];
  onErrorCallback = onErrorCallback || angular.noop;
  finalCallback   = finalCallback   || angular.noop;

  // Create a new list of promises that can "recover" from rejection
  var newListOfPromises = listOfPromises.map(function (promise) {
    return promise.catch(function (reason) {

      // First call the `onErrroCallback`
      onErrorCallback(reason);

      // Change the returned value to indicate that it was rejected
      // Based on the type of `reason` you might need to change this
      // (e.g. if `reason` is an object, add a `rejected` property)
      return 'rejected:' + reason;

    });
  });

  // Finally, we create a "collective" promise that calls `finalCallback` when resolved.
  // Thanks to our modifications, it will never get rejected !
  $q.all(newListOfPromises).then(finalCallback);
}

See, also, this short demo.

One way, would be to attach a .catch handler indidually in your service:

function asyncCall(urls){
    var calls = urls.map(makeSomeCall).
                map(function(prom){ return prom.catch(e){ /* recover here */});
    return $q.all(calls);
};

Another way would be to implement a settle method that is like $q.all but keeps track of all results. Stealing from my answer here:

function settle(promises){
     var d = $q.defer();
     var counter = 0;
     var results = Array(promises.length);
     promises.forEach(function(p,i){ 
         p.then(function(v){ // add as fulfilled
              results[i] = {state:"fulfilled", promise : p, value: v};
         }).catch(function(r){ // add as rejected
              results[i] = {state:"rejected", promise : p, reason: r};
         }).finally(function(){  // when any promises resolved or failed
             counter++; // notify the counter
             if (counter === promises.length) {
                d.resolve(results); // resolve the deferred.
             }
         });
     });
})

You can handle multiple promises as such:

var promiseArr = ["id0","id3","id2"].map(makePromise);

settle(promiseArr).then(function(results){
    var failed = results.filter(function(r){ return r.state === "rejected"; });
    var failedValues = failed.map(function(i){ return i.value; });
    var done = results.filter(function(r){ return r.state === "fulfilled"; });
     var doneValues = done.map(function(i){ return i.value; }); 
});

Which gives you access to all results of the promise, regardless if it failed or not, and let you recover with more granularity.

Your service should handle that aggregation since it's the one returning a promise on everything. One example would be to do:

if(failed.length > 0){
     throw new Error("The following failed..."); // some info about all failed
}
发布评论

评论列表(0)

  1. 暂无评论