Is there a possible way implementing Promise inside angular.foreach?

前端 未结 2 1536
情书的邮戳
情书的邮戳 2021-01-28 15:33
 var sanitizedresult=[];
    angular.forEach(voteResult, function(value, key) {
      // console.log(value.poll_watcher_id);
      var param={
        id : value.candida         


        
相关标签:
2条回答
  • 2021-01-28 16:16

    I think you will have to write your own function to loop rather than using angular.forEach.

    This is done using recursion here

    Something like below:

    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);
    
    0 讨论(0)
  • 2021-01-28 16:25
    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);
    

    There are no errors but still the sanitizedresult is empty what will be the possible cause why the "sanitizedresult" is empty

    0 讨论(0)
提交回复
热议问题