5

In my web application, I have a series of ajax calls that are fired rapidly. On the server, these need to be processed in the same order as they are sent from the client.

I have been using the async: false configuration in jQuery to do this. However this causes the GUI to become very sluggish while it blocks for calls to finish. With async: true the GUI is responsive, but the requests are not always processed in order.

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

NOTE: I don't have a "list" of requests to process. The requests are generated on the fly, so I need to be able to stuff them into some sort of a FIFO queue when they are generated, then consume the queue with some process.

1
  • 1
    you can call each one when the previous one is finished. Commented Jul 24, 2012 at 21:22

1 Answer 1

7

It can be done easily 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/

Sign up to request clarification or add additional context in comments.

7 Comments

I think done could have arguments .done(function(a1, a2){...})
@Sheikh Heera: yep, but I cannot get how it's possible to do that for all deferreds (in case if we chain them, not run simultaneously). If only we pass manually arguments in secondAjax
OK, the problem is I don't "have" all the calls I'm going to make when this process starts...
@pimvdb: look at the comment above: "OK, the problem is I don't "have" all the calls I'm going to make when this process starts" --- so OP doesn't have all the deferreds in one place, so he needs to be able to add piped requests (that's actually why I didn't use a single $.when()
Ah, my apologies. (I thought just wrapping the first call with $.when isn't very useful.)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.