Reputation: 57
I know that there are better ways to do this and tools such as serve-index already exist as an npm package to list a directory structure, but I wanted to test this out on my as I am still rather new to using Node.js and JavaScript.
Currently, my code is as follows, and I am confused as to why my array is empty.
let directoryTree = [];
let directoryList = new Promise((resolve, reject) => {
resolve(fs.readdir(path.join(__dirname, '..'), (err, fileList) => {
for (file of fileList) {
console.log(file);
directoryTree.push(file);
}
}));
}).then(() => console.log(directoryTree))
.catch((err) => console.log(error));
What gets displayed is
[]
app
files
node_modules
package-lock.json
package.json
This indicates to me that the promise is being resolved before readdir finishes executing, otherwise the empty array wouldn't be logged first. I believe that something may be incorrect in my usage of promises then, but I might be wrong. I appreciate any advice!
Upvotes: 0
Views: 48
Reputation: 16908
You can call resolve()
to resolve the promise when the callback is done fetching the data asynchronously.
Then when the data is fetched and resolved you would get the list of files in the then()
callback:
new Promise((resolve, reject) => {
fs.readdir(path.join(__dirname, '..'), (err, fileList) => {
err ? reject(err) : resolve(fileList); //resolve with list of files
});
})
.then((list) => console.log(list))
.catch((err) => console.log(err));
Upvotes: 1
Reputation: 6718
You're using Promise
incorrectly.
The syntax is (from MDN):
const myFirstPromise = new Promise((resolve, reject) => {
// do something asynchronous which eventually calls either:
//
resolve(someValue); // fulfilled
// or
reject("failure reason"); // rejected
});
Refactoring:
let directoryList = new Promise((resolve, reject) => {
fs.readdir(path.join(__dirname, '..'), (err, fileList) => {
if (err) reject(err)
else resolve(fileList)
});
})
// directoryList is a Promise that could reject or resolve
directoryList.then(() => console.log(directoryTree))
.catch((err) => console.log(error));
Upvotes: 0