Return the concatenation of callbacks result called within a loop

javascript, mongodb, node.js

Solution

Keep track of how many results you're still waiting for and then call a callback when done:

function getCurrentScore(callback) {
    var teamScores = "", teamsLeft = teams.length;
    for(var i=0 ; i<teams.length; i++) {
        (function(i){
            PingVoteModel.count({"votedTo": "TEAM"+(i+1)}, function( err, count) {
                teamScores += "<Team" + (i+1) + "> " + count + "\t";
                if (--teamsLeft === 0) {
                    callback(teamScores);
                }
            });
        }(i));
    }
}

Problem

My data is in MongoDB. I am trying to update the score when initiated. However, I need to make several queries depending upon loop. At the end I would like to get the concatenated results of all the callbacks and then call a function with this concatenation result. ``` function getCurrentScore() { var teamScores = ""; (function(){ for(var i=0 ; i< teams.length; i++) { (function(i){ PingVoteModel.count({"votedTo": "TEAM"+(i+1)}, function( err, count) { teamScores += "<Team" + (i+1) + "> " + count + "\t"; }); }(i)); } }()); return teamScores; } ``` How can I get concatenated teamScore ?

Original source