x = getData(); y = getMoreData(x); z = getMoreData(y); getData(function(x){ getMoreData(x, function(y){ getMoreData(y, function(z){ ... }); }); }); It happens when you have lots of callback func4ons in your code! It gets harder to work with them the more of them you have in your code and it gets par4cularly bad when you need to do loops, try-‐catch blocks and things like that.
require('thunkify'); var request = require('request'); var get = thunkify(request.get); co(function *(){ var a = yield get('http://google.com'); var b = yield get('http://yahoo.com'); var c = yield get('http://cloudup.com'); console.log(a[0].statusCode); console.log(b[0].statusCode); console.log(c[0].statusCode); })() 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[0].statusCode); console.log(res[1].statusCode); console.log(res[2].statusCode); })() // Error handling co(function *(){ try { var res = yield get('http://badhost.invalid'); console.log(res); } catch(e) { console.log(e.code) // ENOTFOUND } })()
var app = module.exports = koa(); // x-response-time function *responseTime(next){ var start = new Date; yield next; var ms = new Date - start; this.set('X-Response-Time', ms + 'ms'); } // logger function* logger(next){ var start = new Date; yield next; var ms = new Date - start; if ('test' != process.env.NODE_ENV) { console.log('%s %s - %s', this.method, this.url, ms); } } // response function* respond(next){ yield next; if ('/' != this.url) return; this.body = 'Hello World'; } // composed middleware var all = compose([ responseTime, logger, respond ]); app.use(all); if (!module.parent) app.listen(3000);