Last active
June 21, 2016 17:50
-
-
Save hunan-rostomyan/e30c72fa4086d553bc49ffd145c75395 to your computer and use it in GitHub Desktop.
Asynchronous forEach
This file contains 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
// 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