How to avoid nested functions when using AJAX?

Successive asynchronous calls are rude. Is there a more readable solution?

The problem is this:

ajaxOne(function() {
  // do something
  ajaxTwo(function() {
    // do something
    ajaxThree()
  });
});

where anonymous functions are callbacks called when the server responds.

I use a third-party API to call AJAX, so I need a general solution.

+5
source share
4 answers

functional programming to the rescue! jsdeferred allows you to write your example as follows:

next(ajaxOne).next(ajaxTwo).next(ajaxThree).error(function(e){alert('An error happened:' + e)})

"" ajaxOne/Two/Three . , , ajax.

+3

, Ok , , ...

ajaxOne(function(result) { handleAjaxOneCallback(result, someExtraNeededArg); } );

function handleAjaxOneCallback(result, someExtraNeededParam) {
  // do something

  ajaxTwo(function(result) { handleAjaxTwoCallback(result, myFoo, myBar); });
}

function handleAjaxTwoCallback(result, foo, bar) {
  // do something

  ajaxThree(/* ... */);
}
+1

, JavaScript, jQuery ajax. POST . . , . switch, :

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 worked fine for me.

Best, Renee

Edit:

After some time, I found out that Promises is a much better approach to solve this problem.

+1
source

If you don’t need a closure area in your callbacks that you probably don’t want, you can simply put the callbacks in separate functions and call them by their name. as:

var ajaxOne = function() {
    doTheAjax(callbackOne);
}
var callbackOne = function() {
    //funny things ...
    doTheAjax(callbackTwo);
}
var callbackTwo = function() {
    //even more funny things ...
}
0
source

All Articles