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

Return the concatenation of callbacks result called within a loop

本文关键字:结果 回调 返回 调用 循环      更新时间:2023-09-26

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

如何获得串联的团队分数?

跟踪您仍在等待的结果数量,然后在完成后调用回调:

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

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