关于异步文件处理的编程问题

2020-07-06 14:25:58 +08:00
 milu666
/**
* files [ 'Orthogroups.txt', 'pfam_final.txt', 'txt.txt', 'txt2.txt' ]
/

files.forEach(async file => {
const filrdir: string = path.join(TXTFilesPath, file);
if (file !== 'txt.txt' && file !== 'txt2.txt') {
return;
}
fs.stat(filrdir, (err, stats) => {
if (err) {
console.error(err);
return;
}
if (stats.isFile()) {
// 创建一个文件流
const inStream = fs.createReadStream(filrdir);
const rl = readline.createInterface(inStream);
console.log('filrdir', filrdir);
// 开始解析操作
rl.on('line', async line => {
const fastaName = line.split(':')[0];
const idList = line.split(':')[1];
let temList = idList.trim().split(' ');
temList = [...new Set(temList)];
try {
await temList.forEach((ele: string) => {
this.proteinObject[ele] = fastaName;
});
} catch (e) {
console.error(e);
}
});
}
});
});


files 是一个长度为 4 的数组,然后后面 filrdir 是能建立 txt.txt 与 txt2.txt 两个文件流的,但是最后 this.proteinObject 却始终只存储了一个文件的内容。我知道是异步的原因导致的,但是还是不理解。希望哪个大哥解解惑
1792 次点击
所在节点    Node.js
3 条回复
974879409
2020-07-06 16:40:32 +08:00
libook
2020-07-09 15:26:16 +08:00
里面用了 this,但是所有层级都是箭头函数,箭头函数没有 this,冒泡查找 this 对象,那么外层遇到的第一个 this 就是当前代码所在的 module,也就是说你每次循环都共用了同一个 this,覆盖了同一个 this.proteinObject[ele]。

Array 的 forEach 以及 Readline 的 on 方法内传入的 callback 是异步执行的,比如你代码里针对 4 个文件名的 forEach 过程不会等着前一个处理完再处理下一个,而是一旦前一个进入了异步 io 过程下一个就开始处理了,几乎相当于同时在对两个 txt 进行 io 操作,如果希望能够同步顺序执行应该用 for 循环,处理过程用 async 函数或 promise 封装,在 for 循环里 await 调用,确保上一个处理完再进入下一个循环处理下一个。

不确定你要做什么,如果希望深入讨论的话,建议详细描述一下需求。
milu666
2020-11-11 23:25:31 +08:00
@libook 想感谢,但不会。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/687564

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX