Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- })
Advertisement
Add Comment
Please, Sign In to add comment