var sanitizedresult=[];
angular.forEach(voteResult, function(value, key) {
// console.log(value.poll_watcher_id);
var param={
id : value.candidate_id
}
CandidateService.getCandidatInfo(param).then(function(success){
// console.log(success);
var row = {
ballot_name: success,
vote_count: value.count
}
console.log(row);
sanitizedresult.push(row);
},function(fail){
console.log(fail);
});
});
如何延迟循环的迭代以使其等待promise的响应
答案 0 :(得分:1)
我认为你必须编写自己的函数来循环而不是使用angular.forEach。
这是使用递归here
完成的如下所示:
var sanitizedresult=[];
var processVotes = function(voteResult,idx){
var param={
id : voteResult[idx].candidate_id
}
CandidateService.getCandidatInfo(param).then(function(success){
// console.log(success);
var row = {
ballot_name: success,
vote_count: value.count
}
console.log(row);
sanitizedresult.push(row);
if((idx+1) < voteResult.length){
processVotes(voteResult,idx+1);
}else{
//use sanitizedResult here -- maybe a function call
}
},function(fail){
console.log(fail);
if((idx+1) < voteResult.length){
processVotes(voteResult,idx+1);
}else{
//use sanitizedResult here -- maybe a function call
}
});
}
processVotes(voteResult,0);
答案 1 :(得分:0)
var sanitizedresult=[];
var processVotes = function(voteResult,idx){
var param={
id : voteResult[idx].candidate_id
}
CandidateService.getCandidatInfo(param).then(function(success){
// console.log(success);
console.log(idx+"Thi is it");
var row = {
ballot_name: success,
vote_count: voteResult[idx].count
}
console.log(row);
sanitizedresult.push(row);
if(idx < voteResult.length-1){
processVotes(voteResult,idx+1);
}
},function(fail){
console.log(fail);
if(idx < voteResult.length-1){
processVotes(voteResult,idx+1);
}
});
}
processVotes(voteResult,0);
console.log(sanitizedresult);
没有任何错误,但仍然没有错误,因为“sanitizedresult”为空的可能原因