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 ?
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 ?
Share Improve this question edited Aug 13, 2012 at 16:27 Mike Brant 71.4k10 gold badges101 silver badges104 bronze badges asked Aug 13, 2012 at 16:24 RavishRavish 2,4572 gold badges18 silver badges24 bronze badges2 Answers
Reset to default 4Keep 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));
}
}
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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745408716a4626431.html
评论列表(0条)