Atula Atula - 7 months ago 22
Javascript Question

Data returning from $http.get() is not sequence

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.

Answer

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.