Skip to content

Instantly share code, notes, and snippets.

@roboncode
Created June 23, 2015 15:11
Show Gist options
  • Save roboncode/9038ce78fc493458d88f to your computer and use it in GitHub Desktop.
Save roboncode/9038ce78fc493458d88f to your computer and use it in GitHub Desktop.
Asynchronous forEach function
function forEach(list, fn, done, options) {
if (typeof fn !== 'function') {
throw new Error('Second param expected type "function"');
}
var fnDesc = fn.toString();
var next;
var len = list.length;
var index = 0;
var returnVal;
options = options || {};
var iterate = function () {
if (index < len) {
returnVal = fn(list[index], next);
if (returnVal !== undefined) {
iterate = null;
return done(returnVal);
}
index += 1;
if (!next) {
iterate();
}
} else if (typeof done === 'function') {
iterate = null;
done();
}
};
var argsContainer = fnDesc.match(/\(.*?\)\s?\{/gm);
if (argsContainer[0].match(/\bnext\b/gm)) {
next = function () {
setTimeout(iterate, options.delay);
};
}
iterate();
}
// :: Usage :: //
var arr = [1, 2, 3];
forEach(arr, function(item, next) {
console.log('foreach item', item);
next();
}, function(){
console.log('we are done')
}, {
delay: 1000
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment