转换流用于组合可读流和可写流。数据块在两个流之间的转换是通过transform()方法完成的。
来看下面的生成器,它每1000 毫秒就会生成一个递增的整数:
async function* ints() {
// 每1000 毫秒生成一个递增的整数
for (let i = 0; i < 5; ++i) {
yield await new Promise((resolve) => setTimeout(resolve, 1000, i));
}
}
下面的代码创建了一个TransformStream 的实例,通过transform()方法将每个值翻倍:
async function* ints() {
// 每1000 毫秒生成一个递增的整数
for (let i = 0; i < 5; ++i) {
yield await new Promise((resolve) => setTimeout(resolve, 1000, i));
}
}
const { writable, readable } = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk * 2);
}
});
向转换流的组件流(可读流和可写流)传入数据和从中获取数据,与本章前面介绍的方法相同:
async function* ints() {
// 每1000 毫秒生成一个递增的整数
for (let i = 0; i < 5; ++i) {
yield await new Promise((resolve) => setTimeout(resolve, 1000, i));
}
}
const { writable, readable } = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk * 2);
}
});
const readableStreamDefaultReader = readable.getReader();
const writableStreamDefaultWriter = writable.getWriter();
// 消费者
(async function() {
while (true) {
const { done, value } = await readableStreamDefaultReader.read();
if (done) {
break;
} else {
console.log(value);
}
}
})();
// 生产者
(async function() {
for await (let chunk of ints()) {
await writableStreamDefaultWriter.ready;
writableStreamDefaultWriter.write(chunk);
}
writableStreamDefaultWriter.close();
})();
04-07
2万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)