Skip to content

Instantly share code, notes, and snippets.

@mbeloshitsky
Created September 6, 2010 16:10
Show Gist options
  • Save mbeloshitsky/567197 to your computer and use it in GitHub Desktop.
Save mbeloshitsky/567197 to your computer and use it in GitHub Desktop.
/* async forEach (continuation pass style) */
function forEach (list, cb) {
var i = 0;
function next() {
cb(null, list[i], function () {
i++;
if (i == list.length)
cb('end')
else
next()
})
}
next()
}
/* Example usage */
/* Here we use simple async strategy: insert process.nextTick after
* every 10 items. */
var handler = (function () {
var i = 0;
return function (err, data, done) {
if (err) return
/* Do something with our data */
console.log(data)
/* insert nextTick sometimes */
if (i++ % 10 == 0) {
process.nextTick(done)
} else {
done()
}
}
})()
var arr = [1,2,3,4,5,6,7,8];
forEach(arr, handler)
@mbeloshitsky
Copy link
Author

Tip: replace process.nextTick(done) with setTimeout(done, 1) and this code would work in browser (in my chromium all ok).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment