How to return a promise when writestream finishes?
This question already has an answer here:
你会想使用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!
});
}
You need to return the Promise
before the operation was done.
Something like:
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/55514.html
上一篇: 如何从回调函数创建返回承诺的函数