The code below only executes the first await can someone tell me what the problem is
const { readFile } = require("fs");
const getText = (path) => {
return new Promise((reject, resolve) => {
readFile(path, "utf8", (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
};
async await function
const start = async () => {
try {
const fir = await getText("./path/first.txt");
const sec = await getText("./path/second.txt"); //not working !!!!!!!
console.log(fir,sec);
} catch (error) {
console.log(error);
}
};
start();
output:
hello this is the first text file
The contents of second.txt are not displayed. On the contrary if I comment out the following line
const fir = await getText("./path/first.txt");
Then the contents of second.txt are displayed.
PS: The file paths are correct and the files are not empty
Note the parameter order;
return new Promise((reject, resolve) => {
...should be...
return new Promise((resolve, reject) => {
As it is now,
else resolve(data);
...will due to the confused naming actually reject with the result and ending up logging just the error.