3

我的数据在 MongoDB 中。我正在尝试在启动时更新分数。但是,我需要根据循环进行几个查询。

最后我想得到所有回调的连接结果,然后用这个连接结果调用一个函数。

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

如何获得串联的 teamScore ?

4

2 回答 2

4

跟踪您仍在等待多少结果,然后在完成后调用回调:

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));
    }
}
于 2012-08-13T16:35:38.543 回答
3

通过使用流控制库,在处理许多这样的异步函数时,您可以使您的生活更轻松,并使您的代码更易于阅读;目前,我选择的库是async。在这种情况下,您可以使用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();

结果:

$ node test.js
<Team1> 61
<Team2> 49
<Team3> 51
<Team4> 17
<Team5> 26
<Team6> 51
<Team7> 68
<Team8> 23
<Team9> 17
<Team10> 65
于 2012-08-13T16:39:53.780 回答