Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid nested functions when using AJAX?

Sequential Asynchronous calls are gross. Is there a more readable solution?

The problem is this is hard to follow:

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

where the anonymous functions are callbacks that are called on server response.

I'm using a third party API to make the AJAX calls, so I need a generic solution.

like image 642
Fletcher Moore Avatar asked May 12 '10 12:05

Fletcher Moore


2 Answers

functional programming to the rescue! jsdeferred lets you write your example like so:

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

each of the "sequential" ajaxOne/Two/Three functions receives the returned result of its predecessor as parameter. If you need to pass in additional parameters, you can expose them in a global object before you invoke your ajax chain.

like image 186
fbuchinger Avatar answered Sep 20 '22 02:09

fbuchinger


If you have only one nested function, it's Ok to leave it as is, but if you have several nested calls, you should consider writing these callbacks in a separate method, and calling it from the nested function...

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(/* ... */);
}
like image 25
Pablo Cabrera Avatar answered Sep 19 '22 02:09

Pablo Cabrera