Friday, March 23, 2018
javascript - How to return a promise when writestream finishes?
Answer
Answer
I have such a function, which create a write stream and then write the string array into the file. I want to make it return a Promise once the writing is finished. But I don't know how I can make this work.
function writeToFile(filePath: string, arr: string[]): Promise {
const file = fs.createWriteStream(filePath);
arr.forEach(function(row) {
file.write(row + "\n");
});
file.end();
file.on("finish", ()=>{ /*do something to return a promise but I don't know how*/});
}
Thank you for any comment!
Answer
You'll want to use the Promise
constructor:
function writeToFile(filePath: string, arr: string[]): Promise {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(filePath);
for (const row of arr) {
file.write(row + "\n");
}
file.end();
file.on("finish", () => { resolve(true); }); // not sure why you want to pass a boolean
file.on("error", reject); // don't forget this!
});
}
Subscribe to:
Post Comments (Atom)
plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
-
This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year. Unlike many other programm...
-
I need to do the following: My current address looks like: https://www.domain.com I want to redirect with htaccess: www.domain.com TO https:...
-
using namespace std; So far in my computer science courses, this is all we have been told to do. Not only that, but it's all tha...
No comments:
Post a Comment