V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
milu666
V2EX  ›  Node.js

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

  •  
  •   milu666 · 2020-07-06 14:25:58 +08:00 · 1763 次点击
    这是一个创建于 1361 天前的主题,其中的信息可能已经有所发展或是发生改变。
    /**
    * 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 却始终只存储了一个文件的内容。我知道是异步的原因导致的,但是还是不理解。希望哪个大哥解解惑
    3 条回复    2020-11-11 23:25:31 +08:00
    974879409
        1
    974879409  
       2020-07-06 16:40:32 +08:00
    libook
        2
    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
        3
    milu666  
    OP
       2020-11-11 23:25:31 +08:00
    @libook 想感谢,但不会。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   952 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 21:08 · PVG 05:08 · LAX 14:08 · JFK 17:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.