Nested asynchronous calls using AngularJS

218 Views Asked by At

I'm working on a small project using AngularJS and I'm making various asynchronous calls that are beginning to get messy. I know there has got to be a better way to make these calls but I'm not sure how. This is what I have:

asyncCall1(someArgument,function(asyncCall1Response) {
  // do some stuff
  asyncCall2(asyncCall1Response.someAttribute,function(asyncCall2Response) {
    // do some more stuff
    asyncCall3(asyncCall2Response.someAttribute,function(asyncCall3Response) {
        // finish doing stuff...or maybe call asyncCall4?!
    });
  });
});

What is the correct way to use an asynchronous call's response as arguments being passed into another asynchronous call?

3

There are 3 best solutions below

0
On

One way of handling asynchronous calls you can use $q. It returns multiple promises.

0
On

You can use chain promise, you can read about here: AngularPromises

Consider asyncCall1 returns promise so we can write:

        asyncCall1.then(function(response1){

          // ...
          // pass data from response to other async call
          return asyncCall2(response1);
          }).then(function(response2){

          // ...

          return asyncCall3(response2);
        }).then(function(resonse3){
            // .....

        },
        function(error) {

        });

The advantage of 'chain promises' is:

  • you use only one error callback for all async tasks
  • the code seems clearer (no async pyramid)
0
On

I like this way:

asyncCall1(arguments1)
.then(asyncCall2)
.then(asyncCall3)
.then(doneFn);

What gets returned from the asyncCall1:s successHandler is passed as an argument to asyncCall2.

Sample: jsfiddle