3 ms·
What's the specific problem? Why do you need the results to be ordered? If you really do need to order the results, just attach a sequential ID to each request,
by jey 19y ago
What's the specific problem? Why do you need the results to be ordered? If you really do need to order the results, just attach a sequential ID to each request, then hold a priority queue of results sorted by request ID. Pseudo-code follows:
next_request_id = 0;
next_response_id = 0;
// the following code assumes there's a PriorityQueue class implementing a
// priority queue with push(object, priority) and pop() operations
response_queue = new PriorityQueue();
function send_request(request) {
request.request_id = next_request_id;
next_request_id++;
ajax_send(request);
}
function receive_response(response) {
response_queue.push(response, response.request_id);
while(!response_queue.empty()
&& response_queue.top().request_id == next_response_id) {
handle_response(response_queue.pop());
next_response_id++;
}
}
The above code isn't very robust as it doesn't deal with requests that die in transit and never return a response, etc.
- morris 19y agoRight - this is what I'm about to try to implement (and I think I'd trash the entire queue if a response isn't returned within some timeout limit and display a subsequent error message). I don't know if this is the best practice though and as this seems like a pretty generic AJAX problem, it feels like there should be a pretty generic solution...
- jey 19y agoI doubt most AJAX applications are that reliant on request/response ordering. However, a priority queue is the generic solution. :-)