Node.js: Array looping with async

To be honest, Node.js based asynchronous pattern makes me sick! It can be the worst idea to combine synchronous based coding pattern you’ve learned since first year in computer school. One of very special case of this sickening pattern is to use array based iteration (which is by default, synchronous) to process your data each by each asynchronously and do something else afterwards. Imagine you get code like this :

// data = [{_id: "1", childData: "1"}, {id: "2", childData: "2"}, {id: "3", childData: "2"});
// sum = [{_id: "1", sum: 500}, {_id: "2", sum: 600}]
db.data.find({}, function(err, datas) {
    var count = 0;
    for(idx in datas) {
        // Do MongoDB's relation query somewhere else
        db.childData.findOne({_id: datas[idx].childData}, function(err, childData) {
            count += childData.sum;
        });
    }

    // Show data output
    console.log(count)
});

Read More