Generator based flow-control goodness for nodejs and the browser, using thunks or promises, letting you write non-blocking code in a nice-ish way.
a note to performance:
On my machine 30,000 sequential stat()s takes an avg of 570ms, while the same number of sequential stat()s with co() takes 610ms, aka the overhead introduced by generators is extremely negligable.
Article on
More on Co module:
https://github.com/visionmedia/co
callback hell (http://callbackhell.com/)
asyncFn1(input, function(err, res1) {
if(err) {
// handle error
return;
}
asyncFn2(result1, function(err, res2) {
// just shorthand expression
if(err) //handle error and return
asyncFn3(res2, function(err, res3) {
// just shorthand expression
if(err) //handle error and return
asyncFn4(res3, function(err, res4) {
// just shorthand expression
if(err) //handle error and return
doFinalizationLogic(res4);
});
});
});
});
With co and thunkify
var co = require('co');
var thunkify = require('thunkify');
asyncFn1 = thunkify(asyncFn1);
asyncFn2 = thunkify(asyncFn2);
asyncFn3 = thunkify(asyncFn3);
asyncFn4 = thunkify(asyncFn4);
// sequential
co(function* () {
res1 = yield asyncFn1(input);
res2 = yield asyncFn2(res1);
res3 = yield asyncFn3(res2);
res4 = yield asyncFn4(res3);
doFinalizationLogic(res4);
});
// parallel
var request = require('request');
var get = thunkify(request.get);
co(function *(){
var a = get('http://google.com');
var b = get('http://yahoo.com');
var c = get('http://cloudup.com');
var res = yield [a, b, c];
console.log(res);
})()