JQuery synchronous non-blocking ajax calls

In my web application, I have a series of ajax calls that start quickly. On the server, they must be processed in the same order in which they are sent from the client.

I used async: falsejQuery configuration for this. However, this leads to the fact that the graphical interface becomes very slow when it blocks the completion of calls. It async: trueresponds with a GUI, but requests are not always handled in order.

Is there an alternative non-blocking way to queue ajax requests, so the next one is only sent after the previous one is finished?

NOTE. I do not have a β€œlist” of requests for processing. Requests are generated on the fly, so I need to be able to write them to some FIFO queue when they are created, and then consume the queue with some process.

+5
source share
1 answer

This can be easily done with jQuery promises :

function firstAjax() {
    return $.ajax({...});
}

function secondAjax() {
    return $.ajax({...});
}

firstAjax().pipe(secondAjax).pipe(...).done(function() {
    alert('all requests have successfully finished');
});

or

$.when(firstAjax()).pipe(secondAjax).pipe(...).done(function() {
    alert('all requests have successfully finished');
});

http://jsfiddle.net/zerkms/WQcVD/1/

+6
source

All Articles