Created
January 9, 2010 17:23
-
-
Save blaine/272992 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
// Returns a single promise that emits success or error when the given promises | |
// are complete. | |
// | |
// var promises = require('promise-group') | |
// promises.group(promise1, promise2).addCallback(...) | |
// | |
exports.group = function() { | |
return new PromiseGroup(Array.prototype.slice.call(arguments)).promise; | |
} | |
function PromiseGroup(promises) { | |
var promise = new process.Promise(), | |
promiseCount = 0, | |
started = false, | |
responses = {} // holds values and their name, | |
// we don't know what order they will finish | |
for (name in promises) { | |
var p = promises[name]; | |
promiseCount++; | |
p.addCallback(function(value) { | |
promiseCount--; | |
responses[name] = value; | |
if (started && promiseCount == 0) { | |
promise.emitSuccess(responses); | |
} | |
}) | |
.addErrback(function () { | |
promise.emitError(); | |
}); | |
} | |
// Don't allow promises to start emitting success on the | |
// parent promise unless we've queued them all up. | |
started = true; | |
// check in case all the promises finished before we got here. | |
if (promiseCount == 0) { | |
promise.emitSuccess(responses); | |
} | |
this.promise = promise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment