hanu
hanu

Reputation: 397

how to use a for loop inside $q.all in angularjs

I am trying to repeat the loop ,make a call and hold all promises.Here is my code:

loadpages:function(id,pages){
 var msg =[];
 var finalList =[];
 $q.all([
    for(var i=1;i<=pages;i++)
        this.getPages(id,i).then(function(promise){
            msg[i]= promise.data;
        })
    }),
  ]).then(function() {
    for(var j=1;j<=pageNo;j++){
        finalList.push(msg[j]);
    }
  })

  getPages:function(id,pageNo){
 data.payload = {
                id: id,
                page: pageNo,               
            };
            var promise = $http.post( url,data); 
            return promise;
        },
}

I am getting an error when I keep a for loop inside $q.all. How to get all list ,hold all promises and make a finallist?

Upvotes: 0

Views: 595

Answers (1)

Simon H
Simon H

Reputation: 21017

Loop outside of $q, not inside - try:

    var promises = [];
    for(var i=1;i<=pages;i++) {
        promises.push(this.getPages(id,i).then(function(res){
            return res.data;
        }))
    }
    $q.all(promises).then(function(answers) {....

Upvotes: 1

Related Questions