readable.iterator([options])


  • options <Object>
    • destroyOnReturn <boolean> 当设置为 false 时,对异步迭代器调用 return,或在使用 for await...of 迭代时通过 breakreturnthrow 退出,不会销毁流。默认值: true
  • 返回:<AsyncIterator> 用于消费流。

此方法创建的迭代器允许用户在 for await...of 循环被 returnbreakthrow 退出时选择取消销毁流,或者如果在迭代过程中流发出了错误,则迭代器应销毁该流。

【The iterator created by this method gives users the option to cancel the destruction of the stream if the for await...of loop is exited by return, break, or throw, or if the iterator should destroy the stream if the stream emitted an error during iteration.】

const { Readable } = require('node:stream');

async function printIterator(readable) {
  for await (const chunk of readable.iterator({ destroyOnReturn: false })) {
    console.log(chunk); // 1
    break;
  }

  console.log(readable.destroyed); // false

  for await (const chunk of readable.iterator({ destroyOnReturn: false })) {
    console.log(chunk); // Will print 2 and then 3
  }

  console.log(readable.destroyed); // True, stream was totally consumed
}

async function printSymbolAsyncIterator(readable) {
  for await (const chunk of readable) {
    console.log(chunk); // 1
    break;
  }

  console.log(readable.destroyed); // true
}

async function showBoth() {
  await printIterator(Readable.from([1, 2, 3]));
  await printSymbolAsyncIterator(Readable.from([1, 2, 3]));
}

showBoth();