First I have to admit, I'm relatively new to JavaScript, but I recently encountered the same problem while using the jQuery ajax function. I had to upload a couple of documents via POST to a server in a certain order. Nesting all the call backs would have produced completely messed up code. I thought about a solution after reading the answers and came up with a solution that worked fine me. It uses only one function with a switch clause to differentiate the different callback invocations:
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 this is not a good idea, please let me know. As I said, I'm not a JavaScript expert but I it worked pretty well for me.
Best,
René
Edit:
After a while I found out that Promises are a much better approach to solve this problem.