How to return a promise when writestream finishes? [duplicate]

天涯浪子 提交于 2019-12-09 13:31:55

问题


I have such a function, which create a write stream and then write the string array into the file. I want to make it return a Promise once the writing is finished. But I don't know how I can make this work.

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

Thank you for any comment!


回答1:


You'll want to use the 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!
  });
}



回答2:


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


来源:https://stackoverflow.com/questions/39880832/how-to-return-a-promise-when-writestream-finishes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!