writestream 完成后如何返回承诺? [英] How to return a promise when writestream finishes?
本文介绍了writestream 完成后如何返回承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样一个函数,它创建一个写流,然后将字符串数组写入文件.我想让它在写作完成后返回一个 Promise.但我不知道如何才能做到这一点.
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<boolean> {
const file = fs.createWriteStream(filePath);
arr.forEach(function(row) {
file.write(row + "
");
});
file.end();
file.on("finish", ()=>{ /*do something to return a promise but I don't know how*/});
}
感谢您的任何评论!
推荐答案
您需要使用 Promise
构造函数:
You'll want to use the Promise
constructor:
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 + "
");
}
file.end();
file.on("finish", () => { resolve(true); }); // not sure why you want to pass a boolean
file.on("error", reject); // don't forget this!
});
}
这篇关于writestream 完成后如何返回承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文