所以我正在浏览一个名为candidates
的数组,并使用数组中的每个项目执行某些任务,最后将结果推送到Firebase candfb
。这是代码:
var candidates = json.stageCandidates.candidate;
var list = [];
for (var i = 0; i < 20; i++) {
var candidate = [];
var id = candidates[i].candidateId;
async.parallel([
function(callback) {
votesmart.getDetailedBio(id, function(err, json) {
if (!err && json.bio != undefined)
candidate.bio = json.bio;
callback();
});
},
function(callback) {
votesmart.getAddress(id, function(err, json) {
if (!err && json.address != undefined)
candidate.address = json.address.office[0];
callback();
});
},
function(callback) {
votesmart.getRating(id, function(err, json) {
if (!err && json.candidateRating != undefined)
candidate.ratings = json.candidateRating;
callback();
});
},
function(callback) {
votesmart.getVotes(id, function(err, json) {
if (!err && json.bills != undefined)
candidate.votes = json.bills;
callback();
})
},
function(callback) {
votesmart.getStances(id, function(err, json) {
if (!err && json.npat != undefined)
candidate.stances = json.npat;
callback();
})
}
], function() {
candfb.push(candidate);
// res.send(candidate);
})
};
现在的问题是,即使正好推送了20个项目(在循环中硬编码),也会有一些项目重复,有些项目被跳过。某些项目可能是唯一的,而其他项目可能有多达3个副本被推送到Firebase。我也检查过,数组candidates
没有重复项。
我怀疑这可能是由于我使用async.parallel()
,但我不确定要改变什么以使其有效。
答案 0 :(得分:3)
试试这个,它应该解决你的问题。将同步for循环与异步调用混合时,这是一个常见的错误。你需要关闭我,否则它会被改变。
var candidates = json.stageCandidates.candidate;
var list = [];
for (var i = 0; i < 20; i++) {
(function(i){
var candidate = [];
var id = candidates[i].candidateId;
async.parallel([
function(callback) {
votesmart.getDetailedBio(id, function(err, json) {
if (!err && json.bio != undefined)
candidate.bio = json.bio;
callback();
});
},
function(callback) {
votesmart.getAddress(id, function(err, json) {
if (!err && json.address != undefined)
candidate.address = json.address.office[0];
callback();
});
},
function(callback) {
votesmart.getRating(id, function(err, json) {
if (!err && json.candidateRating != undefined)
candidate.ratings = json.candidateRating;
callback();
});
},
function(callback) {
votesmart.getVotes(id, function(err, json) {
if (!err && json.bills != undefined)
candidate.votes = json.bills;
callback();
})
},
function(callback) {
votesmart.getStances(id, function(err, json) {
if (!err && json.npat != undefined)
candidate.stances = json.npat;
callback();
})
}
], function() {
candfb.push(candidate);
// res.send(candidate);
})
})(i)
};