Created
September 2, 2014 15:33
-
-
Save dustingetz/9365786981b891af08bf to your computer and use it in GitHub Desktop.
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
/** | |
* Turns an array of promises into a promise for an array. If any of | |
* the promises gets rejected, the whole array is rejected immediately. | |
* @param {Array*} an array (or promise for an array) of values (or | |
* promises for values) | |
* @returns a promise for an array of the corresponding values | |
*/ | |
// By Mark Miller | |
// http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled | |
Q.all = all; | |
function all(promises) { | |
return when(promises, function (promises) { | |
var countDown = 0; | |
var deferred = defer(); | |
array_reduce(promises, function (undefined, promise, index) { | |
var snapshot; | |
if ( | |
isPromise(promise) && | |
(snapshot = promise.inspect()).state === "fulfilled" | |
) { | |
promises[index] = snapshot.value; | |
} else { | |
++countDown; | |
when( | |
promise, | |
function (value) { | |
promises[index] = value; | |
if (--countDown === 0) { | |
deferred.resolve(promises); | |
} | |
}, | |
deferred.reject, | |
function (progress) { | |
deferred.notify({ index: index, value: progress }); | |
} | |
); | |
} | |
}, void 0); | |
if (countDown === 0) { | |
deferred.resolve(promises); | |
} | |
return deferred.promise; | |
}); |
Author
dustingetz
commented
Sep 2, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment