Lub*_*bor 5 javascript fs node.js promise typescript
我有这样一个函数,它创建一个写流,然后将字符串数组写入文件.写完后,我想让它返回一个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*/});
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的评论!
Ber*_*rgi 15
你会想要使用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!
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8359 次 |
| 最近记录: |