Browse files

allow forEach to complete even if it's array grows.

  • Loading branch information...
1 parent 8696792 commit 76db4aff3daa22e8149c05db793ad05aa9e01d50 @rektide committed Jul 31, 2012
Showing with 30 additions and 4 deletions.
  1. +15 −4 lib/async.js
  2. +15 −0 test/test-async.js
View
19 lib/async.js
@@ -76,22 +76,33 @@
async.nextTick = process.nextTick;
}
- async.forEach = function (arr, iterator, callback) {
+ async.forEach = function (arr, iterator, callback, skip) {
callback = callback || function () {};
+ skip = skip || 0;
if (!arr.length) {
return callback();
}
- var completed = 0;
+ var completed = skip;
+ var initialLength = arr.length;
_forEach(arr, function (x) {
+ if (skip > 0) {
+ --skip;
+ return;
+ }
iterator(x, function (err) {
if (err) {
callback(err);
callback = function () {};
}
else {
completed += 1;
- if (completed === arr.length) {
- callback(null);
+ if (completed === initialLength) {
+ if (arr.length <= initialLength) {
+ callback(null);
+ }
+ else {
+ async.forEach(arr, iterator, callback, completed);
+ }
}
}
});
View
15 test/test-async.js
@@ -528,6 +528,21 @@ exports['forEach no callback'] = function(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){
var args = [];
async.forEachSeries([1,3,2], forEachIterator.bind(this, args), function(err){

0 comments on commit 76db4af

Please sign in to comment.