提问者:小点点

writestream完成时如何返回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*/});
}

谢谢您的任何评论!


共2个答案

匿名用户

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

匿名用户

在完成操作之前,您需要返回承诺
类似于:

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) });
    });
}