Skip to content

Instantly share code, notes, and snippets.

@blaine
Created January 9, 2010 17:23
Show Gist options
  • Save blaine/272992 to your computer and use it in GitHub Desktop.
Save blaine/272992 to your computer and use it in GitHub Desktop.
// 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