One day I needed to wait on a couple async requests. I could have used: Q, Syncify.js, async.js, Step.js, or any number of other solid libraries... A dependency for just one tiny back corner of my app :(
Instead I wrote ~500 bytes that did the job. Here it is (and on GitHub):
window.these = function() {
if( !(this instanceof these) ) { return new these( arguments ); }
this.functions = [].concat.apply( [], [].slice.call( arguments[0] ) );
this.results = {};
};
these.prototype.thenThis = function( cb ) {
var instance = this, count = this.functions.length, fn;
while( fn = this.functions.shift() ) {
fn( function( key, value ) {
instance.results[key] = value;
if( !--count ) { cb( instance.results ); }
} );
}
return this;
};
Copy/paste the code above into your project. Or, if you must:
bower install these-then-this
Pass functions to these
as either an array
or multiple arguments. Then call thenThis
on
the result with a callback:
these(
function( cb ) {
cb( 'sync', 'some' + 'sync' + 'work' );
},
function( cb ) {
setTimeout( function() { cb( 'async', 'delayed' ); }, 1000 );
}
).thenThis( function( results ) {
alert( JSON.stringify( results, undefined, 2 ) );
} );
You can also check on the progress:
var those = these(
function( cb ) { cb( 'quick', 1 ); },
function( cb ) { setTimeout( function() { cb( 'slow', 2 ); }, 1000 ) }
).thenThis( function( results ) {
alert( JSON.stringify( results, undefined, 2 ) );
} );
setTimeout( function() {
alert(
"quick: " + those.results.quick + ", " + // -> 1
"slow: " + those.results.slow // -> undefined
);
}, 250 );