Ad
How To Make Async Function That Resolves Promise When Readline On('close') Event Is Called Inside It (Typescript)?
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
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error
Ad