首页 > 解决方案 > 如何在其中调用readline on('close')事件(Typescript)时生成解析promise的异步函数?

问题描述

我有这个片段:

private readFile() {
    var innerPackageMap = new Map<string,  DescriptorModel>();

    // Start reading file.
    let rl = readline.createInterface({
        input: fs.createReadStream(MY_INPUT_FILE)
    });

    // event is emitted after each line
    rl.on('line', function (this: ReadRepository, line: string) {
             // parsing of line into innerPackageMap omitted
        }
    );


    rl.on('close', function () {
            // reaction on finish of the file 

        }
    );
}

我喜欢做的是让这个函数异步,所以我可以将执行链接到文件完全读取的那一刻,即调用rl.on('close')的那一刻。我怎么能那样做?

标签: node.jstypescriptasynchronousasync-await

解决方案


要从基于回调的东西中创建一个 Promise,请使用 Promise 构造函数:

private readFile(): Promise<Map<string, DescriptorModel>> {
  return new Promise((resolve, reject) => { // <----- added this
    let innerPackageMap = new Map<string, DescriptorModel>();

    // Start reading file.
    let rl = readline.createInterface({
      input: fs.createReadStream(MY_INPUT_FILE)
    });

    // event is emitted after each line
    rl.on('line', function (this: ReadRepository, line: string) {
      // parsing of line into innerPackageMap omitted
    });

    rl.on('close', function () {
      // reaction on finish of the file 
      resolve(innerPackageMap); // <----- added this
    });
  });
}

推荐阅读