Created
May 18, 2016 02:14
-
-
Save drKnoxy/6ff5e13fc9a9e9e91cdc74e723d6dabd to your computer and use it in GitHub Desktop.
an implementation of allResolved for angularJS
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
// NOTE: $q.all will reject if one of the promises is bad, so we can't use it here | |
// and have instead replicateed $Q.allResolved | |
function allResolved(promises) { | |
var deferred = $q.defer(), // our aggregate promise | |
counter = 0, // know when to resolve our deferred | |
results = []; // where we collect the ordered results of each promise | |
angular.forEach(promises, function(promise, key) { | |
counter++; | |
// might be a value, wrap it up to be safe | |
$q.when(promise).then(function(value) { // success | |
if (results.hasOwnProperty(key)) return; | |
results[key] = value; | |
if (!(--counter)) deferred.resolve(results); | |
}, function(reason) { // fail | |
if (results.hasOwnProperty(key)) return; | |
results[key] = reason.data; // discard the wrapper | |
if (!(--counter)) deferred.resolve(results); | |
}); | |
}); | |
if (counter === 0) { | |
deferred.resolve(results); | |
} | |
return deferred.promise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment