为什么我的“等待”线路没有按预期工作?

问题描述 投票:0回答:1

这是我在 Node.JS 中的代码

  const fs = require('fs');
  const readline = require('readline');
  const filePath = 'the/path/to/the/file';
  const linesPerChunk = 20;
  const readStream = fs.createReadStream(filePath, { encoding: 'utf8' });
  const rl = readline.createInterface({
    input: readStream,
    crlfDelay: Infinity
  });

  let lines = [];

  rl.on('line', async (line) => {
    lines.push(JSON.parse(line));

    if (lines.length === linesPerChunk) {
      await processLines(lines);
      lines = [];
    }
  });

  rl.on('close', async () => {
    // Process any remaining lines (less than chunk size)
    if (lines.length > 0) {
      await processLines(lines);
    }
  });

  async function processLines(lines) {
    console.log("process lines");
    // Do something with the lines (e.g., print them)
    try {
      const returnData = await someaction();
      console.log(returnData);
      console.log('Done for a chunk.');
      return returnData;
    } catch (error) {
      console.log(error);
    }
  }

第一遍进展顺利,但在线上

lines = [];
整个文件被加载到
lines
变量中,就好像系统一直在处理新行一样,即使我应该在处理之前
await
函数的结果更多线路。

然后它立即进入

close
事件并尝试立即处理整个文件(因此除了所有其他文件之外还尝试重新处理我已经处理过的块)。

我在这里缺少什么? 我希望每个块都以顺序方式一一处理(或者实际上是并行处理,但保证没有单行被处理多次)。

javascript node.js asynchronous async-await readline
1个回答
0
投票

第一遍很顺利,但是上线了lines = [];整个文件是 加载到lines变量中,就好像系统一直在处理新的一样 即使我应该等待函数的结果 在处理更多行之前。

您正在使用流,并且等待只会推迟任何异步操作的处理,直至其完成。您需要在处理流时暂停和取消暂停流。这是一种方法。

如果您想对传入线路进行一些处理,另一种解决方案可能是使用转换流

默认情况下 readline 接口不支持暂停,您可以使用 TP 库检查here

© www.soinside.com 2019 - 2024. All rights reserved.