Skip to content

Instantly share code, notes, and snippets.

@jed
Created November 5, 2009 01:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jed/226589 to your computer and use it in GitHub Desktop.
Save jed/226589 to your computer and use it in GitHub Desktop.
a class method for aggregating promises
process.Promise.prototype.combine = function() {
var args = Array.prototype.slice.call( arguments ),
count = args.length,
results = new Array( count ),
index = 0,
self = this;
if ( count == 1 && args[0] instanceof Array )
return arguments.callee.apply( self, args[0] );
args.forEach( function( promise ) {
var thisIndex = index++;
promise.addErrback( function() {
results[ thisIndex ] = arguments;
self.emitError.apply( self, results )
});
promise.addCallback( function() {
results[ thisIndex ] = arguments;
if ( !--count )
self.emitSuccess.apply( self, results );
});
});
return self;
}
// this example loads and compiles two external scripts,
// and fires a single event once both are loaded.
var path = module.filename.replace( /[^\/]+$/, "" ),
dependencies = [ "sha1.js", "base64.js" ],
promises = dependencies
.map( function( file ) { return path + file } )
.map( require( "posix" ).cat );
(new process.Promise).combine( promises ).addCallback( function() {
for ( var i = 0, len = arguments.length; i < len; i++ )
process.compile( arguments[ i ][ 0 ], dependencies[ i ] );
// now you can call any functions in the scripts
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment