返回循环中调用的回调结果的串联
Return the concatenation of callbacks result called within a loop
我的数据在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
相关文章:
- 将web服务回调的结果绑定到Javascript中的调用函数
- 返回循环中调用的回调结果的串联
- 从回调函数返回 AJAX 结果
- MongoDB:$addToSet Meteor中的重复结果回调
- node.js+MySQL;JSON结果-回调问题&没有响应客户端
- 如何通过回调访问nodejs中的mongodb计数结果
- 而循环和回调返回不同的结果
- 如何显示查询回调数据结果仅从开始
- Node.JS- R,Python大量计算识别回调何时返回并存储该结果
- 咖啡脚本化的 ajax 调用结果在实际成功时失败回调
- Meteor.js HTTP.get 获取 JSON 引号并解析结果似乎包含一个回调函数
- 如何使用异步并行将所有回调结果合并到最终回调中
- 根据多个回调结果的结果执行最终回调
- 我是否需要为每个具有等待结果回调的方法关闭
- 我想要一些在另一个回调函数内部的结果
- 使用 AJAX 回调更新挖空可观察数组会生成随机排序的结果
- 为什么我在 JavaScript 中的回调不适用于异步结果
- 为什么异步并行回调会返回意外结果
- 承诺链接:在next-then回调中使用上一个承诺的结果
- Node.js回调错误和结果澄清