Nice article. Be sure to read the comments, as the author links to a library that makes the second example easy to rewrite in a short and elegant way. https://github.com/caolan/async#forEach
Also the first example, the cache hitting and missing, could be rewritten with async, too.
async.waterfall([
function(callback) {
asynchronousCache.get("id:3244", callback);
},
function(myThing, callback) {
if (myThing == null) {
asynchronousDB.query("SELECT * from something WHERE id = 3244", callback)
} else {
callback(myThing)
}
},
function(myThing, callback) {
// We now have a thing from the DB or cache, do something with result
// ...
}
]);
From a readability standpoint I'll take the "old" version any day:
function getFromDB(foo) {
var result = asynchronousCache.get("id:3244");
if ( null == result ) {
result = asynchronousDB.query("SELECT * from something WHERE id = 3244");
}
return result;
}
Also the first example, the cache hitting and missing, could be rewritten with async, too.