close()
ReadableStreamDefaultController
接口的 close()
方法关闭关联的流。
读取器仍然可以从流中读取任何先前入队的块。一旦这些块被读取,流就会关闭,并且不再有可用数据。
异常
异常 | 描述 |
---|---|
TypeError | 当源对象不是 ReadableStreamDefaultController 时抛出。 |
示例
import { ReadableStream } from 'k6/experimental/streams';
import { setTimeout } from 'k6/timers';
export default async function () {
let currentNumber = 0;
const stream = new ReadableStream({
start(controller) {
const fn = () => {
if (currentNumber % 8 == 0) {
// Close the stream when the number is divisible by 8
controller.close();
return;
}
if (currentNumber < 10) {
controller.enqueue(++currentNumber);
setTimeout(fn, 1000);
return;
}
controller.close();
};
setTimeout(fn, 1000);
},
});
const reader = stream.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(`received number ${value} from stream`);
}
}