Tag Archives: asynchronous

Finalize – JavaScript Asynchronous Requests Queue

Most web apps send lots of asynchronous http requests. Sometimes you need to know when some selected requests are finished so that you can pass to the next step.

The following function can be used for creating a queue with asynchronous requests using JavaScript and be notified when the queue is empty again (all selected requests are finished):

function Finalize(_callback) {
	var count = 0,
	    exec  = false;

	if((typeof _callback !== 'undefined') && (_callback !== null)) {
		this.exec = function() {
			exec = true;
			if(count === 0) {
				_callback();
			}
		}
		this.queue = function() {
			count++;
			return function() {
				count--;
				if(exec && (count === 0)) {
					_callback();
				}
			}
		}
	} else {
		this.exec  = function() {};
		this.queue = function() {};
	}
}

Usage:

var request_set = new Finalize(function() {
    // Code inside this function will be executed at the end
});

// To add an item to the queue
var first_item = request_set.queue();

// Let's add another item
var second_item = request_set.queue();

// The code inside the final callback will only be called after
// all the items in queue are completed.
// Let's consider we have two async requests:
jQuery.get('http://example.com', function(data) {
    // We now have the response from the first request
    // Remove one item from queue by calling the item's name
    first_item();
});

// The items can also be removed by passing them directly as callback
jQuery.get('http://example.com', second_item);

// You can even skip declaring items and create them on the fly as the callback function
jQuery.get('http://example.com', request_set.queue());

// After you've added all items to the queue we need to execute it
request_set.exec();

The function can also be used in NodeJS.