I have to interact with a remote api that forces me to chain requests. Thats a callback-hell in asynchronous mode:
// pseudocode: ajax(request_object, callback) ajax(a, function() { ajax(b(a.somedata), function() { ajax(c(b.somedata), function() { c.finish() } }) })
It would be much more readable in sync mode:
sjax(a) sjax(b(a.somedata)) sjax(c(b.somedata)) c.finish()
But Sjax is evil :) How do I do that in a nice not-so-evil and readable way?
The jQuery library provides a way to make any callback function waiting for multiple Ajax calls. This method is based on an object called Deferred. A Deferred object can register callback functions based on whether the Deferrred object is resolved or rejected. Here is an example of the Deferred object.
There is a requirement to make multiple AJAX calls parallelly to fetch the required data and each successive call depends on the data fetched in its prior call. Since AJAX is asynchronous, one cannot control the order of the calls to be executed.
Since Ajax calls are asynchronous, the application will not 'pause' until an ajax call is complete, and simply start the next call immediately. JQuery offers a handler that is called when the call is successful, and another one if an error occurs during the call.
You could have a single function which is passed an integer to state what step the request is in, then use a switch statement to figure out what request needs to be make next:
function ajaxQueue(step) { switch(step) { case 0: $.ajax({ type: "GET", url: "/some/service", complete: function() { ajaxQueue(1); } }); break; case 1: $.ajax({ type: "GET", url: "/some/service", complete: function() { ajaxQueue(2); } }); break; case 2: $.ajax({ type: "GET", url: "/some/service", complete: function() { alert('Done!'); } }); break; } } ajaxQueue(0);
Hope that helps!
Don't use anonymous functions. Give them names. I don't know if you're able to do what I wrote below though:
var step_3 = function() { c.finish(); }; var step_2 = function(c, b) { ajax(c(b.somedata), step_3); }; var step_1 = function(b, a) { ajax(b(a.somedata), step_2); }; ajax(a, step_1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With