Salal Aslam
Salal Aslam

Reputation: 1377

How to check for completion of two simultaneous requests with Restangular

I am doing 2 requests using Restangular,

  Restangular.all('clients').getList().then(function(clients) {
    $scope.clients = clients;
  });
  Restangular.all('suppliers').getList().then(function(suppliers) {
    $scope.suppliers = suppliers;
  });

I want to run some code after it they finish, how can i do so?

Upvotes: 1

Views: 652

Answers (1)

PSL
PSL

Reputation: 123739

You could use $q.all and add both the promises as input. And you would need to inject $q.

  var clientsPromise = Restangular.all('clients').getList().then(function(clients) {
     $scope.clients = clients;
  });
  var suppliersPromise = Restangular.all('suppliers').getList().then(function(suppliers) {
     $scope.suppliers = suppliers;
  });

   $q.all([clientsPromise, suppliersPromise])
     .then(function(results){ //This will execute only when both the promises have been fulfilled
       //Do something;
   });

For more readability you could as well do:-

 function populateClients(){
    return Restangular.all('clients').getList().then(function(clients) {
       $scope.clients = clients;
    });
 }

 function populateSuppliers(){
    return Restangular.all('suppliers').getList().then(function(suppliers) {
      $scope.suppliers = suppliers;
   });
 }

 $q.all([populateClients(), populateSuppliers()]).then(doSomethingFn, handleError);

Success callback of q.all will run only when both the promises are resolved, if one of them fails it will go to catch block and you can use finally which will run when all are fulfilled.

Upvotes: 1

Related Questions