Created
March 20, 2016 16:43
-
-
Save Prateek479/db9745c58acb07b62fcd to your computer and use it in GitHub Desktop.
Async parallel forEach and async forEach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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