Skip to content

Instantly share code, notes, and snippets.

@hunan-rostomyan
Last active June 21, 2016 17:50
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 hunan-rostomyan/e30c72fa4086d553bc49ffd145c75395 to your computer and use it in GitHub Desktop.
Save hunan-rostomyan/e30c72fa4086d553bc49ffd145c75395 to your computer and use it in GitHub Desktop.
Asynchronous forEach
// Callback-style (recursion explicit)
function forAsync(items, fn, next) {
var max = items.length;
function rec(i) {
if (i === max) {
next();
}
fn(items[i], i);
rec(i + 1);
}
rec(0);
}
// Promise-style (recursion in reduce)
function forAsync(items, fn) {
return items.reduce(function(promised, item, i) {
return promised.then(function() {
return fn(item, i);
});
}, Promise.resolve());
}
// Usage
forAsync([1,2,3,4], function(item, i) {
setTimeout(function(){
console.log(item);
}, item * 500);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment