1

while I'm getting a json object from Restangular ,another rest url function has been called(before first response comes)

Restangular.all("..").getList("..").then(
     function(data){
       $scope.dataList = data.dataList;       
     }, function errorCallback() {
        alert("error");
     }
);  

here before initializing datalist it is calling another function parallely? how can I avoid this?

thanks.

SFernando
  • 1,074
  • 10
  • 35

1 Answers1

0

If you need to call your services in specific order then you have two options:

Nesting service callbacks. This solution will prevent execution of the next ajax call until the previous is finished:

 Restangular.all("..").getList("..").then(
         function(data){
           Restangular.secondFunction("..").getList().then(
           function (data2) {
              // both data and data2 are available
           });

         }, function errorCallback() {
            alert("error");
         }
    );  

Use $q.all() function which waits for the array of deferred objects to finish:

var promises = [];

promises.push(Restangular.all("..").getList(".."));
promises.push(Restangular.secondFunction("..").getList());

$q.all(promises).then(function (results) {
  for (var i=0; i<results.length; i++)
  {
     // all ajax calls have finished now you can iterate through the results 
  }
});

BTW there is no such thing like parallel execution in javascript.

Community
  • 1
  • 1
Marian Ban
  • 8,158
  • 1
  • 32
  • 45