Last active
August 29, 2015 14:17
-
-
Save JamesMessinger/4e0dc57f350eb8c09a75 to your computer and use it in GitHub Desktop.
Async for loop in JavaScript
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
/** | |
* An asynchronous for-each loop | |
* | |
* @param {array} array The array to loop through | |
* | |
* @param {function} done Callback function (when the loop is finished or an error occurs) | |
* | |
* @param {function} iterator | |
* The logic for each iteration. Signature is `function(item, index, next)`. | |
* Call `next()` to continue to the next item. Call `next(Error)` to throw an error and cancel the loop. | |
* Or don't call `next` at all to break out of the loop. | |
*/ | |
function asyncForEach(array, done, iterator) { | |
var i = 0; | |
next(); | |
function next(err) { | |
if (err) { | |
done(err); | |
} | |
else if (i >= array.length) { | |
done(); | |
} | |
else if (i < array.length) { | |
var item = array[i++]; | |
setTimeout(function() { | |
iterator(item, i - 1, next); | |
}, 0); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment