0

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/

4

3 回答 3

3

如果它们确实需要顺序,那么每个响应处理程序都可以简单地调用下一个。像这样的东西:

$.ajax({
    // options for the first call
}).done(function() {
    $.ajax({
        // options for the second call
    }).done(function () {
        // and so on
    });
});
于 2013-10-11T14:58:46.797 回答
0

这段代码工作正常。该错误是由于其他原因造成的。您可以查看我的查询中发布的小提琴。

于 2013-12-30T14:19:10.137 回答
-1

之后url: queue[0].options.url,就可以使用了async: false,

async: true,是 jQuery AJAX 的默认行为

于 2013-10-11T16:15:50.360 回答