Skip to content

Instantly share code, notes, and snippets.

@ffbit
Forked from trukhinyuri/asyncForeach.js
Created May 20, 2013 07:30
Show Gist options
  • Select an option

  • Save ffbit/5610856 to your computer and use it in GitHub Desktop.

Select an option

Save ffbit/5610856 to your computer and use it in GitHub Desktop.
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