Is is that hard to move the stuff over into a module?
EDIT: Updated the code.
function asyncLoop(iterations, func, callback) {
var index = 0;
var done = false;
var loop = {
next: function() {
if (done) {
return;
}
if (index < iterations) {
index++;
func(loop);
} else {
done = true;
callback();
}
},
iteration: function() {
return index - 1;
},
break: function() {
done = true;
callback();
}
};
loop.next();
return loop;
}
exports.asyncFor = asyncLoop;
And a small test:
// test.js
var asyncFor = require('./aloop').asyncFor; // './' import the module relative
asyncFor(10, function(loop) {
console.log(loop.iteration());
if (loop.iteration() === 5) {
return loop.break();
}
loop.next();
},
function(){console.log('done')}
);
Rest is up to you, it's impossible to make this 100% generic.