Created
September 6, 2010 16:10
-
-
Save mbeloshitsky/567197 to your computer and use it in GitHub Desktop.
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
/* 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tip: replace process.nextTick(done) with setTimeout(done, 1) and this code would work in browser (in my chromium all ok).