I have a web app that makes a ton of $.post() requests. The server must receive these in the order that they were created. To guarantee this, I first thought I'd make my own queue that dequeued and fired the next Ajax call after the previous one had completed.
Then I saw there's an async:false option with the you can use with $.ajax().
I've changed all my requests to use $.ajax({ async: false, ... }), but when I monitor them in Firebug, requests are not sent one-by-one, each next request being fired off after the last has received a response.
What is async suppose to do then? How might I pipe my Ajax so that one executes at a time, the next one firing when the last one has completed (received response)?
Instead of using async:false, you could create a function that is called recursively from the callback.
function sendReq( arr ) {
var current = arr.shift(); // Remove the first item from the Array.
$.ajax({
url: current.url, // Use the url from the first item.
success: function( dat ) {
current.func( dat ); // Call the function of the first item.
if( arr.length ) // If there are items left in the Array,
sendReq( arr ); // make a recursive call, sending
} // the remainder of the array.
});
}
// Ordered collection of requests to be made.
var req_set = [
{url:'someurl', func:function( dat ) { /*do something with dat*/ }},
{url:'anotherurl', func:function( dat ) { /*do something with dat*/ }},
{url:'someother', func:function( dat ) { /*do something with dat*/ }}
];
// Start the first call, sending the entire set.
sendReq( req_set );
So basically:
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