-
-
Save 7fe/1116377 to your computer and use it in GitHub Desktop.
When-Then (pseudo javascript Promise)
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(){ | |
if( !(this instanceof when) ) return new when(arguments); //return new instance of itself | |
var self = this; //cached so the syntax of code within the function is more readable | |
self.pending = Array.prototype.slice.call(arguments[0]); //convert arguments passed in to array | |
self.pending_length = self.pending.length; //cache length of the arguments array | |
self.results = []; //container for results of async functions | |
(function(){ // define pass() within this context so that the outer scope of self(this) is available when pass() is executed within the user's async functions | |
self.pass = function(){ | |
self.results.push(arguments); //push async results to cache array | |
if( self.results.length === self.pending_length ) //if all async functions have finished, pass the results to .then(), which has been redefined to the user's completion function | |
self.then.call(self, self.results); | |
}; | |
})(); | |
} | |
when.prototype = { | |
then: function(){ | |
this.then = arguments[0]; //reassign .then() to the user-defined function that is executed on completion. Also ensures that this() can only be called once per usage of when() | |
while(this.pending[0]){ | |
this.pending.shift().call(this, this.pass); //execute all functions user passed into when() | |
} | |
} | |
} | |
//#### TEST CASE 1 #### | |
when( | |
function(pass){ | |
pass(2); | |
}, | |
function(pass){ | |
setTimeout(function(){ | |
pass(1000); | |
}, 1000); | |
}, | |
function(){ | |
setTimeout(function(){ | |
pass(100); | |
}, 100); | |
}, | |
function(){ | |
setTimeout(function(){ | |
pass(2000); | |
}, 2000); | |
} | |
) | |
.then(function(results){ | |
console.log(results); | |
}) | |
//#### TEST CASE 2 (Node.js required) #### | |
var http = require('http'); | |
var get = function(url, pass){ | |
http.get({ host: url, port: 80 }, function(res){ | |
var body = []; | |
res.on('data', function(chunk){ | |
body.push(chunk); | |
}) | |
.on('end', function(){ | |
pass(body.join('')); | |
}); | |
}) | |
.on('error', function(err){ | |
pass(err); | |
}); | |
} | |
when( | |
function(pass){ | |
get('www.google.com', pass); | |
}, | |
function(pass){ | |
get('news.ycombinator.com', pass); | |
}, | |
function(pass){ | |
get('io9.com', pass); | |
} | |
) | |
.then(function(results){ | |
console.log(results); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment