Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.