返回循环内调用的回调结果串联

时间:2012-08-13 16:24:30

标签: javascript node.js mongodb

我的数据在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?

2 个答案:

答案 0 :(得分: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));
    }
}

答案 1 :(得分: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