Chaining Ajax calls in AngularJs

Solution 1:

Yes, this is handled very elegantly by AngularJS since its $http service is built around the PromiseAPI. Basically, calls to $http methods return a promise and you can chain promises very easily by using the then method. Here is an example:

$http.get('http://host.com/first')
   .then(function(result){
    //post-process results and return
    return myPostProcess1(result.data); 
   })
   .then(function(resultOfPostProcessing){
    return $http.get('http://host.com/second'); 
   })
   .then(function(result){
    //post-process results of the second call and return
    return myPostProcess2(result.data); 
   })
   .then(function(result){
      //do something where the last call finished
   });

You could also combine post-processing and next $http function as well, it all depends on who is interested in the results.

$http.get('http://host.com/first')
   .then(function(result){
    //post-process results and return promise from the next call
    myPostProcess1(result.data); 
    return $http.get('http://host.com/second'); 
   })
   .then(function(secondCallResult){
     //do something where the second (and the last) call finished
   });

Solution 2:

The accepted answer is good, but it doesn't explain the catch and finally methods which really put the icing on the cake. This great article on promises set me straight. Here's some sample code based on that article:

$scope.spinner.start();

$http.get('/whatever/123456')
  .then(function(response) {
     $scope.object1 = response.data;
     return $http.get('/something_else/?' + $scope.object1.property1);
  })
  .then(function(response) {
     $scope.object2 = response.data;
     if ($scope.object2.property88 == "a bad value")
        throw "Oh no! Something failed!";
     return $http.get('/a_third_thing/654321');
  })
  .then(function(response) {
     $scope.object3 = response.data;
  })
  .catch(function(error) {
     // this catches errors from the $http calls as well as from the explicit throw
     console.log("An error occured: " + error);
  })
  .finally(function() {
     $scope.spinner.stop();
  });