'Understand Node 14 and async functions
I'm having a little trouble understanding async with Node, I understand how to they work but every now and then I run into these problems that take up a lot of time when trying to soft out.
This function does nothing that I can see happening, is does not console log and does not write the file.
const { writeFile } = require("fs");
const { promisify } = require("util");
const asyncWriteFile = promisify(writeFile);
const writeTxtFile = async () => {
console.log("starting file write");
let files = ["fileone", "filetwo"];
try {
await asyncWriteFile("fileList.txt", "hello", (err) => {
if (err) {
console.log("There was an error with writeFile", err);
return;
}
console.log("file written!");
return true;
});
} catch (error) {
console.log(error);
}
};
//calling with
writeTxtFile().then((status) => {
console.log("status for write: ", status);
});
Then if I make a small change by changing the piece of code
await asyncWriteFile("fileList.txt", "hello", (err) => {
//change to
let res = await asyncWriteFile("fileList.txt", "hello", (err) => {
It creates the file correctly, however, I still don't get any console logs from the function or the call part.
I'm not sure where I'm going wring wuth all this.
Solution 1:[1]
You can't just promisify a function from fs and expect it to work. You might want to look into fs.promises for that.
Now even if that were to work, you are using an await in asyncWriteFile. await will wait for a the function to complete its execution which returns a promise, unlike callbacks, which expect a function to run after it completes execution, using a callback handler there won't cause it to be executed. Here is a version of fs.promises.writeFile that you might want to try.
const { writeFile } = require("fs").promises;
const writeTxtFile = async () => {
console.log("starting file write");
try {
await writeFile("fileList.txt", "hello");
console.log("file written!");
return "Written!";
} catch (error) {
console.log("There was an error with writeFile", error);
return "Not written!";
}
};
//calling with
writeTxtFile().then((status) => {
console.log("status for write: ", status);
});
Output
starting file write
file written!
status for write: Written!
And yes file is indeed written.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rinkesh P |
