Looking at node.js, and avoiding nesting callbacks. I found Async.js, can someone show me how can I rewrite this code using the async.waterfall method?
// db is a mongodb instance
db.open(function(err, client){
client.createCollection("docs", function(err, col) {
client.collection("docs", function(err, col) {
for (var i = 0; i < 100; i++) {
col.insert({c:i}, function() {});
}
console.log('Insert done OK.');
});
});
});
What problems does this naive solution with inner functions have, over the async method?
db.open(openAndInsert);
function openAndInsert(err, client) {
var myCollection = "docs";
client.createCollection(myCollection, openCollection);
function openCollection(err, col) {
client.collection(myCollection, insertIntoCollection);
}
function insertIntoCollection(err, col) {
for (var idx = 0; idx < 100; idx += 1) {
col.insert({c:idx}, function () {});
}
console.log('Insert done OK.');
}
}
The three levels of nesting in the original code seem like a code smell, but I'm not sure either my home rolled or the async solution are universally better. Would anyone prefer just leaving the nested functions as is? If so, how deep would the nesting have to be before going using some type of flow control?