3

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.

Community
  • 1
  • 1
Atula
  • 2,177
  • 2
  • 12
  • 28

3 Answers3

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
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