Skip to content

Commit

Permalink
[api test] Added async.forEachLimit() and associated tests
Browse files Browse the repository at this point in the history
  • Loading branch information
indexzero committed Jun 12, 2011
1 parent cbb0a42 commit 90c80a1
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
36 changes: 36 additions & 0 deletions lib/async.js
Expand Up @@ -133,6 +133,42 @@
};
iterate();
};

async.forEachLimit = function (arr, limit, iterator, callback) {
if (!arr.length || limit <= 0) {
return callback();
}
var completed = 0;
var started = 0;
var running = 0;

(function replenish () {
if (completed === arr.length) {
return callback();
}

while (running < limit && started < arr.length) {
iterator(arr[started], function (err) {
if (err) {
callback(err);
callback = function () {};
}
else {
completed += 1;
running -= 1;
if (completed === arr.length) {
callback();
}
else {
replenish();
}
}
});
started += 1;
running += 1;
}
})();
};


var doParallel = function (fn) {
Expand Down
53 changes: 53 additions & 0 deletions test/test-async.js
Expand Up @@ -491,6 +491,59 @@ exports['forEachSeries error'] = function(test){
setTimeout(test.done, 50);
};

exports['forEachLimit'] = function(test){
var args = [];
var arr = [0,1,2,3,4,5,6,7,8,9];
async.forEachLimit(arr, 2, function(x,callback){
setTimeout(function(){
args.push(x);
callback();
}, x*5);
}, function(err){
test.same(args, arr);
test.done();
});
};

exports['forEachLimit empty array'] = function(test){
test.expect(1);
async.forEachLimit([], 2, function(x, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};

exports['forEachLimit zero limit'] = function(test){
test.expect(1);
async.forEachLimit([0,1,2,3,4,5], 0, function(x, callback){
test.ok(false, 'iterator should not be called');
callback();
}, function(err){
test.ok(true, 'should call callback');
});
setTimeout(test.done, 25);
};

exports['forEachLimit error'] = function(test){
test.expect(2);
var arr = [0,1,2,3,4,5,6,7,8,9];
var call_order = [];

async.forEachLimit(arr, 3, function(x, callback){
call_order.push(x);
if (x === 2) {
callback('error');
}
}, function(err){
test.same(call_order, [0,1,2]);
test.equals(err, 'error');
});
setTimeout(test.done, 25);
};

exports['map'] = function(test){
var call_order = [];
async.map([1,3,2], function(x, callback){
Expand Down

0 comments on commit 90c80a1

Please sign in to comment.