Created
July 30, 2011 08:03
-
-
Save 7fe/1115319 to your computer and use it in GitHub Desktop.
when then JavaScript
This file contains 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
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