Tom Tom - 1 year ago 57
AngularJS Question

Make $q.all fail silently when one promise is rejected

I am geocoding some addresses, sometimes some of them fail. I'd like to be able to get the rest of the results and ignore the failed one so I can display the other coordinates on a map. Currently $q.all will call the errorHandler when one is rejected, so I lose the results of other promises.

$q.all(promises).then(function(coords) {
for (var j = 0;j<coords.length;j+=1) {
//success code
}
}, function(error) {
console.log("Failed",error.type,error.message);
});

Answer Source

What you want is q.allSettled, which isn't implemented in Angular.

Here's a relevant GitHub issue requesting its implementation.

And here is one possible implementation, called allComplete, that you can add to your Angular app:

angular.module('App.services', ['ngResource'])
  .config( function($provide) {
    $provide.decorator("$q", ["$delegate", function($delegate) {
      var $q = $delegate;

      $q.allComplete = function(promises) {

        if(!angular.isArray(promises)) {
          throw Error("$q.allComplete only accepts an array.");
        }

        var deferred = $q.defer();
        var passed = 0;
        var failed = 0;
        var responses = [];

        angular.forEach(promises, function (promise, index) {
          promise
            .then( function(result) {
              console.info('done', result);
              passed++;
              responses.push(result);
            })
            .catch( function(result) {
              console.error('err', result);
              failed++;
              responses.push(result);
            })
            .finally( function() {
              if((passed + failed) == promises.length) {
                console.log("COMPLETE: " + "passed = " + passed + ", failed = " + failed);

                if(failed > 0) {
                  deferred.reject(responses);
                } else {
                  deferred.resolve(responses);
                }
              }
            })
          ;
        });

        return deferred.promise;

      };

      return $q;
    }]);
  })
;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download