获取异步迭代的第一个元素

Get first element of an async iterable

在 nodejs 上,我试图获取文件的第一行。 为此,我正在使用 this answer 中提到的 readline 包。

但是因为我只是想获取第一行,所以我需要获取 readline 对象来输出它的第一个元素。我在 this answer 中找到了如何做到这一点,但它看起来只适用于同步迭代器。

如何获取异步迭代器的第一个元素?

只是 return 在循环的第一次迭代中?从该答案中复制一些代码,并确保 to destroy 在完成仅获取第一行后的流:

async function processLineByLine() {
  const fileStream = fs.createReadStream('input.txt');
  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });
  for await (const line of rl) {
    fileStream.destroy();
    return line;
  }
}

然后 processLineByLine 将 return 解析为第一行内容的 Promise。