I want to fetch data from 3 source URLs different only by id. The result I am getting is fine but not in sequence. My code is :
    
    var data = [{"id":"1"},{"id":"2"},{"id":"3"}];
    var get = [];
    for(i=0;i<(data.length);i++){
    $http.get("server URL"+data[i].id)
    .success(function(data) { 
    get.push(data);
    })
    .error(function(err) {
    console.log(err);
    }); 
    }$scope.data= get;
    
I have done researches and tried things too but could not make it work right.
I have also tried this link but not so useful for me. 
            Asked
            
        
        
            Active
            
        
            Viewed 65 times
        
    3
            
            
        - 
                    Can you snapshot the result pls ? – Deadpool Apr 12 '16 at 06:36
- 
                    I have used a demo of my code so I can't post my actual code's demo. Sorry. – Atula Apr 12 '16 at 06:42
3 Answers
4
            You should use $q.all for this.
var data = [{"id":"1"},{"id":"2"},{"id":"3"}],
    promises = [];
for(i = 0; i < data.length; i++)
    promises.push($http.get("server URL"+data[i].id));
$q.all(promises)
    .then(function(result) {
        $scope.data = result;
    }, function(err) {
        console.log(err);
    });
The result will be an array with results in order of requests.
 
    
    
        Martijn Welker
        
- 5,575
- 1
- 16
- 26
- 
                    I am getting promises.then is not a function error. Can you help me with that? – Atula Apr 12 '16 at 07:12
- 
                    
- 
                    
0
            
            
        You can do something like following:
var data = [{"id":"1"},{"id":"2"},{"id":"3"}];
var get = [];
var i = 0;
function loadDataInSequence(){
  if(i<data.length){
    $http.get("server URL"+data[i].id)
        .success(function(data) { 
                get[i] = data;//calling callback
            loadDataInSequence();
        })
        .error(function(err) {
            console.log(err);
        });
        i++;
  }
}
$scope.data= get;
 
    
    
        Manwal
        
- 23,450
- 12
- 63
- 93
0
            
            
        For these kind of situations, there a library called async. You can use async parallel in place of for loop. There are also helpers like series, and limit for different kind of requirements.
 
    
    
        Ashok Kumar Sahoo
        
- 580
- 3
- 8
- 24
 
    