Permalink
Browse files

callback methods w/ test & docs

  • Loading branch information...
1 parent 03edcad commit 570cf8e16ae6775a10c00302d5b36a7f2d56bf9d @MaZderMind MaZderMind committed Apr 17, 2011
Showing with 38 additions and 0 deletions.
  1. +8 −0 README.md
  2. +6 −0 lib/async.js
  3. +24 −0 test/test-async.js
View
@@ -674,6 +674,9 @@ methods:
alter the concurrency on-the-fly.
* push(task, [callback]) - add a new task to the queue, the callback is called
once the worker has finished processing the task.
+* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued
+* empty - a callback that is called when the last item from the queue is given to a worker
+* drain - a callback that is called when the last item from the queue has returned from the worker
__Example__
@@ -685,6 +688,11 @@ __Example__
}, 2);
+ // assign a callback
+ q.drain = function() {
+ console.log('all items have been processed');
+ }
+
// add some items to the queue
q.push({name: 'foo'}, function (err) {
View
@@ -549,13 +549,19 @@
var tasks = [];
var q = {
concurrency: concurrency,
+ saturated: null,
+ empty: null,
+ drain: null,
push: function (data, callback) {
tasks.push({data: data, callback: callback});
+ if(q.saturated && tasks.length == concurrency) q.saturated();
async.nextTick(q.process);
},
process: function () {
if (workers < q.concurrency && tasks.length) {
var task = tasks.splice(0, 1)[0];
+ if(q.empty && tasks.length == 0) q.empty();
+ if(q.drain && tasks.length + workers == 0) q.drain();
workers += 1;
worker(task.data, function () {
workers -= 1;
View
@@ -1319,3 +1319,27 @@ exports['falsy return values in parallel'] = function (test) {
}
);
};
+
+exports['queue events'] = function(test) {
+ test.expect(3);
+ var q = async.queue(function(task, cb) {
+ // nop
+ cb();
+ }, 3);
+
+ q.saturated = function() {
+ test.ok(q.length() == 3, 'queue should be saturated now');
+ }
+ q.empty = function() {
+ test.ok(q.length() == 0, 'queue should be empty now');
+ }
+ q.drain = function() {
+ test.ok(q.length() == 0 && q.running() == 0, 'queue should be empty now and no more workers should be running');
+ test.done();
+ }
+ q.push('foo');
+ q.push('bar');
+ q.push('zoo');
+ q.push('poo');
+ q.push('moo');
+};

0 comments on commit 570cf8e

Please sign in to comment.