From 3d3d21a3f9cd7bfde17ecd1a81c6eaabbc6344d9 Mon Sep 17 00:00:00 2001 From: calzoneman Date: Sun, 29 Sep 2013 00:27:43 -0500 Subject: [PATCH] Add asyncqueue class --- lib/asyncqueue.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 lib/asyncqueue.js diff --git a/lib/asyncqueue.js b/lib/asyncqueue.js new file mode 100644 index 00000000..f8b3b38c --- /dev/null +++ b/lib/asyncqueue.js @@ -0,0 +1,45 @@ +var AsyncQueue = function () { + this._q = []; + this._lock = false; + this._tm = 0; +}; + +AsyncQueue.prototype.next = function () { + if (this._q.length > 0) { + if (!this.lock()) + return; + var fn = this._q.shift(); + fn(this); + } +}; + +AsyncQueue.prototype.lock = function () { + if (this._lock) + return false; + + this._lock = true; + return true; +}; + +AsyncQueue.prototype.release = function () { + var self = this; + if (!self._lock) + return false; + + self._lock = false; + process.nextTick(function () { + self.next(); + }); + return true; +}; + +AsyncQueue.prototype.queue = function (fn) { + var self = this; + self._q.push(fn); + self.next(); +}; + +AsyncQueue.prototype.reset = function () { + this._q = []; + this._lock = false; +};