I would like to make multiple Ajax calls in a chain. But I also would like to massage the data after each call before making the next call. In the end, when All calls are successful, I would like to run some other code.
I am using Angular $http service for my Ajax calls and would like to stick to that.
Is it possible?
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With