Although I am relatively new to JavaScript, I recently faced a similar issue when using the jQuery ajax function. The task was to upload multiple documents via POST to a server in a specific order. Nesting callbacks seemed like it would lead to messy code. After reading some answers, I devised a solution that worked well for me. I created a single function with a switch statement to handle different callback scenarios:
var callback = function(sCallIdentifier, callbackParameters){
switch(sCallIdentifier){
case "ajaxOne":
doYourStuff(callbackParameters); //do your stuff for ajaxOne
ajaxTwo(function(newCallbackParameters){
/*define a anonymous function as actual method-callback and pass the call-identifier, together with all parameters, to your defined callback function*/
callback("ajaxTwo", newCallbackParameters);
});
break;
case "ajaxTwo":
doYourStuff(callbackParameters);
ajaxThree(function(newCallbackParameters){
callback("ajaxThree", newCallbackParameters);
});
break;
case "ajaxThree":
doYourStuff();
break;
}
});
If there are better alternatives, please feel free to share. While I may not be a JavaScript expert, this approach has proven effective for me.
Best,
René
Edit:
I later discovered that Promises offer a more efficient solution to this problem.