I'm learning more and more about node and the biggest problem I'm having is figuring out truly how asynchronous functions work.
fs.readdir(base, function (err, files) {
if (!files.length) {
console.log('No files');
}
for (var i in files) {
fs.stat(files[i], function (err, stats) {
if (stats.isDirectory()) {
console.log(files[i]);
console.log('FOLDER');
} else {
console.log(files[i]);
console.log('FILE')
}
})
}
});
base
is a folder with two sub-folders in, and a .DS_Store file. The output at the command line will be:
.DS_Store
FILE
/dir/to/file/index.js:115
if (stats.isDirectory()) {
^
TypeError: Cannot read property 'isDirectory' of undefined
My basic understanding now is this problem exists because it's all happening asynchronously - my best guess is that the readdir
callback doesn't 'wait' for the fs.stat
callback to finish? I might be completely misunderstanding it (and really, any good documents to learn from this a base understanding would be helpful).
My next idea is something like promises? They seem to fix many problems with async so that would be my next leap in learning.
Is this 'callback hell'? Are promises the fix? Is there a different way to do this?
via vSanjo
No comments:
Post a Comment