Ravish
Ravish

Reputation: 2447

Return the concatenation of callbacks result called within a loop

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 ?

Upvotes: 3

Views: 2471

Answers (2)

Michelle Tilley
Michelle Tilley

Reputation: 159125

You can make your life much easier and make your code easier to read when dealing with many asynchronous functions like this by using a flow control library; currently, my library of choice is async. In this case, you could use map:

// Stub out some data

PingVoteModel = {
  count: function(options, callback) {
    callback(null, Math.floor(Math.random() * 100));
  }
};

teams = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Now for the real stuff

var async = require('async');

function getCurrentScore() {
  var iterator = function(team, callback) {
    PingVoteModel.count({"votedTo": "TEAM" + team}, function(err, count) {
      callback(null, "<Team" + team + "> " + count);
    });
  };

  async.map(teams, iterator, function(err, results) {
    console.log(results.join("\n"));
  });
}

getCurrentScore();

Results:

$ node test.js
<Team1> 61
<Team2> 49
<Team3> 51
<Team4> 17
<Team5> 26
<Team6> 51
<Team7> 68
<Team8> 23
<Team9> 17
<Team10> 65

Upvotes: 3

JohnnyHK
JohnnyHK

Reputation: 312055

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));
    }
}

Upvotes: 4

Related Questions