Skip to content

Instantly share code, notes, and snippets.

@Prateek479
Created March 20, 2016 16:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Prateek479/db9745c58acb07b62fcd to your computer and use it in GitHub Desktop.
Save Prateek479/db9745c58acb07b62fcd to your computer and use it in GitHub Desktop.
Async parallel forEach and async forEach
function asyncParForEach(array, fn, callback) {
var completed = 0;
if (array.length === 0) {
callback(); // done immediately
}
array.forEach(function(data) {
fn(data, function() {
completed++;
if (completed === array.length) {
callback();
}
});
});
}
function asyncForEach(array, fn, callback) {
array = array.slice(0);
function processOne() {
var item = array.pop();
fn(item, function(result) {
if (array.length > 0) {
setTimeout(processOne, 0); // schedule immediately
} else {
callback(); // Done!
}
});
}
if (array.length > 0) {
setTimeout(processOne, 0); // schedule immediately
} else {
callback(); // Done!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment