Ellone
Ellone

Reputation: 3898

Callback method after multiple asynchronous call

Is there a way to wait for multiple API calls to respond before executing a line code ?

Usually, I use :

APIService.call(parameter).then(function(response) {
   // Do things
   callBack();
});

And this works fine, callBack() is executed after the the APIService.call()'s answer.

But let's say I have 3 different API calls like this :

$scope.var1 = APIService.call1(parameter)
$scope.var2 = APIService.call2(parameter)
$scope.var3 = APIService.call3(parameter)

And I want my callback to be called after the 3 calls answered, meaning after the longest one answers. How could I do that ? I don't want to make nested then because I want my 3 calls to keep being called asynchronously.

Is this doable ?

Upvotes: 2

Views: 72

Answers (2)

Bruno Peres
Bruno Peres

Reputation: 16355

Since you are using AngularJS, you can use $q.all. Do something like:

var promises = [];

promises.push(APIService.call1(parameter));
promises.push(APIService.call2(parameter));
promises.push(APIService.call3(parameter));

$q.all(promises).then(function (values) {
    // you can access the response from each promise
    $scope.var1 = values[0];
    $scope.var2 = values[1];
    $scope.var3 = values[2];
    doSomething();
})

Upvotes: 4

Hussein Salman
Hussein Salman

Reputation: 8226

You can use the $q.all() method, simply pass it an array of promises you want to resolve, what this does is it takes the array of promises and returns a single promise which will resolve once all the original promises have been resolved.

$q.all([
  APIService.call1(parameter),
  APIService.call2(parameter),
  APIService.call3(parameter),
]).then(function(data) {

   //TODO: something...
});

Upvotes: 1

Related Questions