Skip to content

Instantly share code, notes, and snippets.

@trukhinyuri
Last active December 17, 2015 12:38
Show Gist options
  • Select an option

  • Save trukhinyuri/5610794 to your computer and use it in GitHub Desktop.

Select an option

Save trukhinyuri/5610794 to your computer and use it in GitHub Desktop.
Async Foreach
function asyncForeach(array, fn, callback) {
var completed = 0;
var arrayLength = array.length;
if(arrayLength === 0) {
callback();
}
for(var i = 0; i < arrayLength; i++) {
fn(array[i], i, function() {
completed++;
if(completed === arrayLength) {
callback();
}
});
}
}
asyncForeach([1, 2, 3], function(item, index, next_cb) {
setTimeout(function() {
console.log(item)
}, item * 100);
setTimeout(next_cb, 100);
}, function() {
console.log('end');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment