Serialising POST requests jQuery/Javascript
I am working on an application which sends an AJAX POST request (I'm using jQuery currently) every 1500ms. I have noticed that most of the times, these requests succeed within 350-450ms and are sent to the server nicely in the same order as they are generated.
However sometimes, one or two requests take nearly 3-4开发者_JS百科 seconds and they are delivered later. In my application I need to ensure that these requests are received by the server in the same order as they are sent from the client. How do I do that? I am using currently setInterval of 1500ms to call a function (which generates the data to be posted) and which POSTs it using $.ajax(). However, how do I serialise the requests?
Don't know exactly how this would work out in javascript, but you could create a list or array of your request, first in first out type of list, so when ready you push your request or whatever values needed to create your request into the array, after set interval you take from the array and send request. Basically you'll queue your request that way.
One way would be to include a timestamp sent with the js, and on the receiving end, you could add each call to a queue, which you then execute after ordering it by timestamp DESC
.
If you provide more information about what's really happening, maybe you could adjust the interval based on which type of request (eg. how long is the expected response time?)
The following will wait for server response before starting the 1500ms timer to kick off the next request...
$(function() {
var recursive = arguments.callee;
$.post("http://url", { /* data */ }, function() {
setTimeout(recursive, 1500);
});
});
You can't guarantee the order of responses in an asynchronous setup. What you can do, however, is
- add a serial number (or timestamp) on both request and response.
- upon receiving each response, store the results in a global store with the serial number as the key
- Run a separate setInterval process that checks the global store in correct order, process the result and disposes it off.
This will guarantee serialized execution of results. But care needs to be taken for requests that timeout or error out to not stall the subsequent processing.
精彩评论