Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Here's my implementation of `Q.allSettled` for AngularJS, which I've named `allComplete`. Due to a bug in this Gist editor, I had to give this gist a .js extension file name, but this would typically go within your services.js file (depending on your project structure).
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;
}]);
})
;
@benjamingr

This comment has been minimized.

Copy link

commented Sep 3, 2014

This implementation here is wrong - the order of the responses is incorrect.

A much more elegant implementation (minus the decorator) would be something like Q itself does, something like:

$q.allSettled = function (promises) {
    return Q.all(promises.map(function (promise) {
            return Q(promise).then(function(val){ 
                return {state: "fulfilled", value: val };     
            }, function(err){
                return {state: "rejected", reason: err };
            });
        }));
    });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.