typescript writestream 完成后如何返回承诺?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39880832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return a promise when writestream finishes?
提问by Lubor
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.
我有这样一个函数,它创建一个写流,然后将字符串数组写入文件。我想让它在写作完成后返回一个 Promise。但我不知道如何才能做到这一点。
function writeToFile(filePath: string, arr: string[]): Promise<boolean> {
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!
感谢您的任何评论!
回答by Bergi
You'll want to use the Promise
constructor:
你会想要使用Promise
构造函数:
function writeToFile(filePath: string, arr: string[]): Promise<boolean> {
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!
});
}
回答by Nitzan Tomer
You need to return the Promise
before the operation was done.
Something like:
您需要Promise
在操作完成之前返回。
就像是:
function writeToFile(filePath: string, arr: string[]): Promise<boolean> {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(filePath);
arr.forEach(function(row) {
file.write(row + "\n");
});
file.end();
file.on("finish", () => { resolve(true) });
});
}