Skip to content

Instantly share code, notes, and snippets.

@ianwremmel
Created September 19, 2012 23:17
Show Gist options
  • Save ianwremmel/3752975 to your computer and use it in GitHub Desktop.
Save ianwremmel/3752975 to your computer and use it in GitHub Desktop.
Some things in nodejs need to be done synchronously (or, at least, shouldn't be enqueued at the rate a foreach loop will do so). Once I wrote this function three or four times, I decided it was time to put it somewhere easily accessible.
/**
* @file queue.js
* This is an asynchronous queue for nodejs. Initialize it with a callback to
* execute against each item in the queue and (optionally) a queue of items
* against which to operate. Then, execute emitter.emit('next') at the end of
* your callback to trigger each subsequent run. Queue.exec() returns the
* emitter you'll need. Once exec has been called, each time push() is called,
* the pushed item will be execuated against at the end of the queue (if the
* queue is empty, it will be executed imediately).
*/
var events = require('events');
var Queue = function(callback, queue) {
var _queue = queue || [];
var _running = false;
var _callback = callback;
var _emitter = new events.EventEmitter();
var _next = function() {
if (_queue.length) {
var item = _queue.shift();
if (typeof(item) === 'array') {
_callback.apply(this, item);
}
else {
_callback.call(this, item);
}
}
else {
_emitter.emit('empty');
}
};
_emitter.on('next', _next);
return {
push: function(item) {
if (_queue.length === 0 && _running) {
_queue.push(item);
this.exec();
}
else {
_queue.push(item);
}
return _emitter;
},
exec: function() {
_running = true;
for (var i = 0; i < 1; i++) {
process.nextTick(_next);
}
return _emitter;
}
}
};
exports.Queue = Queue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment