Nested axios call functions

Hello,
I have nested function calls. And each function has a axios call in it. I want to execute those nested function calls one by one. However, because of asynchronous nature of axios, this is not working. Functions are getting called in any random sequence.

Each function result is important to its nested function call. So call sequence is important for me. I don’t want to make ajax calls in the .then() method of previous axios call, because my each axios call’s code is quite large.

Could you please suggest some better mechanism to handle this situation?
Thank you in advance!

The correct method is to put the call to the next function inside the then() of the previous one. I’m not sure what the length of the handler code has to do with it.

function function1() {
   $.ajax(....)
   .then(yourcodehere)
   .then(function2);
}
function function2() {
   $.ajax(....)
   .then(yourcodehere)
   .then(function3);
}
...
function1();

Alternatively you can chain directly, little less readable IMO, but doable:

function function1() {
   $.ajax(....);   
}
function function2() {
   //Process the result of the first call here, then
   return $.ajax(....)
}

function function3() {
   //Process the result of the second call here, then
   return $.ajax(....)
}
...
function1().then(function2).then(function3)....;

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.