My application makes concurrent AJAX asynchronous calls to a server which only has 4 threads (Baracudda server, for example). I need to convert my concurrent AJAX async calls into sequential async calls. Is there any mechanism inside jQuery to do it? Please suggest.
Code:
function initiateAJAXRequest() {
var promise = $.ajax({
type: queue[0].options.type,
url: queue[0].options.url,
timeout: queue[0].options.timeout || 3000,
cache: (!queue[0].options.cache) ? queue[0].options.cache : true,
dataType: queue[0].options.dataType,
data: queue[0].options.data
}).promise();
promise.then(function(result) {
console.log(queue[0]);
// I get an error in the line below: "xhr is undefined".
queue[0].dfd.resolve(result);
queue.splice(0, 1);
if(queue.length > 0) {
queue[0].isActiveRequest = true;
initiateAJAXRequest();
}
});
promise.fail(function(xhr, statusText, message) {
queue[0].dfd.reject(arguments);
queue.splice(0, 1);
if(queue.length > 0) {
queue[0].isActiveRequest = true;
initiateAJAXRequest();
}
});
}
function callAJAXAsync(options) {
// Create deferred object. This will manage the promise chain who calls this method.
var deferred = new $.Deferred();
window.queue.push({dfd: deferred, options: options});
window.queue = queue;
if(!window.queue[0].isActiveRequest) {
window.queue[0].isActiveRequest = true;
initiateAJAXRequest();
}
return deferred.promise();
};
This is the code I've written for the framework of my application. A single page can make multiple calls to callAJAXAsync() method. The problem is I get an error in the line commented inside initiateAJAXRequest().
EDIT One thing that strikes me is, I am creating a new deferred object inside callAJAXAsync() method and resolving/rejecting it inside initiateAJAXRequest() method. Is that valid?
SOLUTION This code works fine. The error was due to some other reason. Here is the fiddle that I created just in case... http://jsfiddle.net/LnaPt/