2012-08-13 111 views
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; 
} 

如何获得concatenated teamScore?的

回答

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

感谢横空出世,这种简单的解决方案。 :) – Ravish 2012-08-13 16:52:15

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 
+0

非常感谢布兰登为这样的说明性解决方案。 :) – Ravish 2012-08-13 16:51:32