Skip to content

Commit

Permalink
allow forEach to complete even if it's array grows.
Browse files Browse the repository at this point in the history
  • Loading branch information
rektide committed Aug 1, 2012
1 parent 8696792 commit 3eda642
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/async.js
Expand Up @@ -82,20 +82,21 @@
return callback(); return callback();
} }
var completed = 0; var completed = 0;
_forEach(arr, function (x) { for(var i = 0; i < arr.length; ++i){
var x= arr[i];
iterator(x, function (err) { iterator(x, function (err) {
if (err) { if (err) {
callback(err); callback(err);
callback = function () {}; callback = function () {};
} }
else { else {
completed += 1; completed += 1;
if (completed === arr.length) { if (completed >= arr.length) {
callback(null); callback(null);
} }
} }
}); });
}); }
}; };


async.forEachSeries = function (arr, iterator, callback) { async.forEachSeries = function (arr, iterator, callback) {
Expand Down
15 changes: 15 additions & 0 deletions test/test-async.js
Expand Up @@ -528,6 +528,21 @@ exports['forEach no callback'] = function(test){
async.forEach([1], forEachNoCallbackIterator.bind(this, test)); async.forEach([1], forEachNoCallbackIterator.bind(this, test));
}; };


exports['forEach with growing array'] = function(test){
var arr= [2,3];
var iterations = 0;
async.forEach(arr, function(x, callback){
if (iterations++ == 0) {
arr.push(4);
}
callback();
}, function(){
test.same(arr, [2,3,4]);
test.same(iterations, 3);
test.done();
})
};

exports['forEachSeries'] = function(test){ exports['forEachSeries'] = function(test){
var args = []; var args = [];
async.forEachSeries([1,3,2], forEachIterator.bind(this, args), function(err){ async.forEachSeries([1,3,2], forEachIterator.bind(this, args), function(err){
Expand Down

0 comments on commit 3eda642

Please sign in to comment.