我有这样一个函数,它创建一个写入流,然后将字符串数组写入文件。写完后,我想让它返回一个Promise。但我不知道如何才能做到这一点。
transform: translateX(-5.8%) translateY(-5%) scale(0.884);
感谢您的评论!
答案 0 :(得分:12)
您想要使用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 + "\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!
});
}
答案 1 :(得分:3)
您需要在操作完成之前返回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) });
});
}