node.js - 如何在其中调用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')的那一刻。我怎么能那样做?
解决方案
要从基于回调的东西中创建一个 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
});
});
}
推荐阅读
- jms - IBM MQ - 如何使用多个连接名称连接到队列管理器(一个是故障转移)
- haskell - 在 Haskell 中更改映射中多个键的值
- python - 用双引号括起来时忽略逗号
- excel - 如何将单元格范围复制为电子邮件正文中的位图?
- voyager - Nuxt+Vuetify 和 Directus 哪个更好?
- amazon-web-services - 使用节点后端托管 Angular 前端
- laravel - 更改全日历语言
- powershell - 如何通过powershell列出sharepoint在线目录中的文件
- python - 如何使python函数将封闭变量绑定到值而不是名称
- android - Angular Router Resolve 在任务终止并重新打开 Android Google Chrome 时不起作用