writestream完成时如何返回承诺?
这个问题在这里已经有了答案:
你会想使用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!
});
}
在操作完成之前,您需要返回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) });
});
}
链接地址: http://www.djcxy.com/p/55513.html