返回循环内调用的回调结果串联 [英] Return the concatenation of callbacks result called within a loop
本文介绍了返回循环内调用的回调结果串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据在MongoDB中。我试图在启动时更新分数。
但是,我需要根据循环进行多次查询。
My data is in MongoDB. I am trying to update the score when initiated. However, I need to make several queries depending upon loop.
最后我想获得所有回调的连接结果,然后调用a具有此连接结果的函数。
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;
}
如何获得串联的teamScore?
How can I get concatenated teamScore ?
推荐答案
跟踪你还在等待多少结果,然后在完成后调用回调:
Keep 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));
}
}
这篇关于返回循环内调用的回调结果串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文