Skip to content

Instantly share code, notes, and snippets.

@7fe
Created July 30, 2011 08:03
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 7fe/1115319 to your computer and use it in GitHub Desktop.
Save 7fe/1115319 to your computer and use it in GitHub Desktop.
when then JavaScript
var when = function(funcs){
if(!(this instanceof when)){
return new when(arguments);
}
this.funcs = Array.prototype.slice.call(funcs);
}
when.prototype.then = function(then){
var i = 0,
funcs = this.funcs,
l = funcs.length,
results = [],
// Custom Object replaces func when pass is called
complete = {},
// insure all functions have successfully completed
// before calling then function
try_then = function(){
var i=0;
// insure all functions have run
while(i<l){
if(funcs[i++]!==complete)return;
}
then(results);
// Prevent multiple calls to then
then = function(){};
}
while(i<l)(function(i){
var pass = function(result){
results[i] = result
funcs[i] = complete;
try_then();
}
funcs[i](pass)
})(i++);
};
when(
function(pass){
setTimeout(pass,3000);
},
function(pass){
pass('2nd');
}
)
.then(function(results){
console.log(results);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment