异步迭代


¥Async Iteration

<ReadableStream> 对象支持使用 for await 语法的异步迭代器协议。

¥The <ReadableStream> object supports the async iterator protocol using for await syntax.

import { Buffer } from 'node:buffer';

const stream = new ReadableStream(getSomeSource());

for await (const chunk of stream)
  console.log(Buffer.from(chunk).toString()); 

异步迭代器将消耗 <ReadableStream> 直到它终止。

¥The async iterator will consume the <ReadableStream> until it terminates.

默认情况下,如果异步迭代器提前退出(通过 breakreturnthrow),<ReadableStream> 将被关闭。为防止 <ReadableStream> 自动关闭,使用 readableStream.values() 方法获取异步迭代器并将 preventCancel 选项设置为 true

¥By default, if the async iterator exits early (via either a break, return, or a throw), the <ReadableStream> will be closed. To prevent automatic closing of the <ReadableStream>, use the readableStream.values() method to acquire the async iterator and set the preventCancel option to true.

<ReadableStream> 不得锁定(即,它不得有现有的活动读取器)。在异步迭代期间,<ReadableStream> 将被锁定。

¥The <ReadableStream> must not be locked (that is, it must not have an existing active reader). During the async iteration, the <ReadableStream> will be locked.