Last active
September 7, 2016 00:54
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}]); | |
}) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: