Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safe queue in Javascript or jQuery

I have many asynchronous AJAX calls whose results will get processed. It doesn't matter what order the processing occurs, but the results need to get processed one at a time. So I'd like to simple do my AJAX calls and they all just put their results in a single queue. That queue should then get processed on a single thread. This way the results get processed one at a time as soon as possible.

What's the best way to do this? I'm using jQuery, so happy to take advantage of any facilities it provides for this.

like image 635
at. Avatar asked Jan 17 '11 08:01

at.


1 Answers

Asynchronous does NOT mean 'multiple threads'. Think about many click events firing in a row, before the first click handler is processed. Only one action can be handled at a time, and the others will wait to execute.

Event driven languages like Javascript operate on the basis of a queue. Javascript in the background essentially has one giant queue that events and asynchronous responses get pushed in to. Once a particular piece of processing is complete, the next item from the queue is worked on.

These queues are sometimes known as 'Runloops'. Javascript will spin in an endless loop, retrieving an event from the queue, processing it, and returning back to the queue for another piece of work.

Multithreading can be achieved in (newer) versions of Javascript using Web Workers, but these are explicitly opt-in. Look them up if you're interested.

To answer your question then, just attach a callback to your asynchronous request, and it will complete processing even if another response is returned half way through. The other response will 'wait' until the current event is handled.

like image 200
Josh Smeaton Avatar answered Sep 17 '22 17:09

Josh Smeaton