Skip to content

Instantly share code, notes, and snippets.

@Prinzhorn
Created February 27, 2012 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Prinzhorn/1926219 to your computer and use it in GitHub Desktop.
Save Prinzhorn/1926219 to your computer and use it in GitHub Desktop.
Async forEach
/*
Iterate over all elements and do some async work on each element, but ensure they all get worked on in order
*/
var arr = [1, 2, 3];
asyncForEach(arr, function(next, element) {
console.log(element);
//Simulate async db call
setTimeout(next, 1000);
}, function() {
console.log('iterating done');
});
var asyncForEach = exports.asyncForEach = function(arr, each, all) {
var i = 0;
function next() {
if(i < arr.length) {
i++;
process.nextTick(function() {
each(next, arr[i - 1]);
});
} else {
if(all !== undefined) {
all();
}
}
}
next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment