How to return a promise when writestream finishes?

This question already has an answer here:

  • How do I convert an existing callback API to promises? 17 answers

  • 你会想使用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

    上一篇: 如何从回调函数创建返回承诺的函数

    下一篇: writestream完成时如何返回承诺?