Created
February 27, 2012 18:52
-
-
Save Prinzhorn/1926219 to your computer and use it in GitHub Desktop.
Async 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
/* | |
Iterate over all elements and do some async work on each element, but ensure they all get worked on in order | |
*/ | |
var arr = [1, 2, 3]; | |
asyncForEach(arr, function(next, element) { | |
console.log(element); | |
//Simulate async db call | |
setTimeout(next, 1000); | |
}, function() { | |
console.log('iterating done'); | |
}); |
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
var asyncForEach = exports.asyncForEach = function(arr, each, all) { | |
var i = 0; | |
function next() { | |
if(i < arr.length) { | |
i++; | |
process.nextTick(function() { | |
each(next, arr[i - 1]); | |
}); | |
} else { | |
if(all !== undefined) { | |
all(); | |
} | |
} | |
} | |
next(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment