gpt4 book ai didi

javascript - writestream 完成后如何返回 promise ?

转载 作者:数据小太阳 更新时间:2023-10-29 05:43:14 25 4
gpt4 key购买 nike

我有这样一个函数,它创建一个写入流,然后将字符串数组写入文件。我想让它在编写完成后返回一个 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*/});
}

感谢您的任何评论!

最佳答案

您需要使用 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!
});
}

关于javascript - writestream 完成后如何返回 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39880832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com