Skip to content

Instantly share code, notes, and snippets.

@JGarrido
Last active September 7, 2016 00:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JGarrido/8100714 to your computer and use it in GitHub Desktop.
Save JGarrido/8100714 to your computer and use it in GitHub Desktop.
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
Copy link

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