-
-
Save isaacs/429797 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
function readAllHelps (cb) { | |
var help_text = [] | |
, didError = false | |
function error (er) { | |
if (didError) return undefined | |
didError = true | |
cb(er) | |
} | |
fs.readdir('help', function(er, files) { | |
if (err) return error(er) | |
var len = files.length | |
files.forEach(function (file) { | |
fs.readFile('help/'+file, function(er, data) { | |
if (didError) return undefined | |
if(er) return error(er) | |
help_text[file] = data | |
if (0 === --len) cb(null, help_text) | |
}) | |
}) | |
}) | |
} |
Thanks so much, you're a great help !
I think I now get how to structure my code thanks to your example.
I would never have come up with the counter decrementation to know when to call the callback... Very clever, I'll remember that trick.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try something like this: http://gist.github.com/429797
Note how readAllHelps is abstracted into its own function, so you pass your callback in there, and get notified when all the help files have been read.