Ad

How To Make Async Function That Resolves Promise When Readline On('close') Event Is Called Inside It (Typescript)?

- 1 answer

I have this snippet:

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 

        }
    );
}

What I like to do is to have this function async, so I can chain execution to the moment when the file is completely read, that is when rl.on('close') is invoked. How I could do that?

Ad

Answer

To create a promise out of something which is callback-based, use the promise constructor:

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
    });
  });
}
Ad
source: stackoverflow.com
Ad