Please, I know this question has been answered before. I have read this answer & this article, but I can't figure out how to fix my code yet.
I have created a function
that reads some file's content & returns
a new Promise
. Here it's the function
:
// array of string representing each file's path
const allSpecFiles = [
'/path/to/the/file1.spec.js',
'/path/to/the/file2.spec.js',
'/path/to/the/file3.spec.js'
];
// method to read an individual file content & return a Promise
const readFileContent = file => {
return new Promise((resolve, reject) => {
fs.readFile(file, 'utf8', (err, data) => {
if (err) return reject(err);
return resolve(data);
});
});
};
Now, I'm trying to loop through an array
of strings
storing each file's path
, call the readFileContent()
method & pass current loop's value as its param
with map()
method since I would like to create another array
of strings
with each file's content.
This is what I have tried:
const allSpecFilesArr = allSpecFiles.map(async file => await readFileContent(file));
console.log(allSpecFilesArr); // I get Promise { <pending> }
I have also tried wrapping the whole script
like so:
(async () => {
const allSpecFilesArr = await allSpecFiles.map(file => readFileContent(file));
console.log(allSpecFilesArr); // still prints Promise { <pending> }
})();
What I'm doing wrong?