Reputation: 902
I'm trying to learn more about async, await Promises and all these, I have understood the concept behind it, but I'm getting troubles when it comes to nest logic of these Promises. In theory what I have understood is that the whole async await would make your code look more synchronous, meaning that everything that expects a promise to be the result you use the await. Main goal with this code is to return from the list of directories+files that came from readdirPromisify, filter, and only give me a list of files. using the stat.isFile(). If anyone can help I would appreciate. thanks!
const fs = require("fs");
const { exec } = require("child_process");
const { promisify } = require("util");
const [, , ...args] = process.argv;
const isOptionDirectory = promisify(fs.stat);
const readdirPromisify = promisify(fs.readdir);
const [packageName] = args;
const test = async function() {
const dirs = await readdirPromisify(__dirname);
const files = await dirs.filter(async file => {
const option = await isOptionDirectory(file);
return option.isFile();
});
return files;
};
console.log(test().then(val => console.log(val)));
Upvotes: 0
Views: 699
Reputation: 664195
filter
does not support promises. The promise returned by the async function
will be treated as a truthy value.
You will want to use Promise.all
:
async function test() {
const paths = await readdirPromisify(__dirname);
const options = await Promise.all(paths.map(isOptionDirectory));
return paths.filter((_, i) => options[i].isFile());
}
Upvotes: 1