Domanda

I have an AngularJS service with such async API:

myService.asyncCall(['id0', 'id3', 'id2']).then(function (complexData) {   
  // handle complexData
}).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 ?

È stato utile?

Soluzione

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.

Altri suggerimenti

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
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top