Created
November 5, 2009 01:00
-
-
Save jed/226589 to your computer and use it in GitHub Desktop.
a class method for aggregating promises
This file contains hidden or 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
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 file contains hidden or 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
// 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