这个问题类似于我的另一个问题 https://stackoverflow.com/questions/62457644/use-readablestream-with-response-to-return-html-from-fetch-event-of-service-work/62459039#62459039但考虑到内部的异步性质ReadableStream
.
这是我现在的测试代码:
const stream = new ReadableStream({
start(c) {
let i = 1
const t = setInterval(test, 5e2)
function test() {
c.enqueue("<h1>Yellow!</h1>")
if (i++ === 5) {
clearInterval(t)
c.close()
}
}
}
})
event.respondWith(new Response(stream, {headers: {"content-type": "text/html"}}))
上面的代码不是由浏览器呈现的,我不知道为什么。根据网上的例子 https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#Examples看起来应该有效。但它似乎没有阅读任何内容enqueue
items.
请注意,在我的其他问题中,答案至少给出了第一个响应:
const createStream = () => new ReadableStream({
start(controller) {
controller.enqueue("<h1 style=\"background: yellow;\">Yellow!</h1>")
controller.close()
}
})
const secondStream = createStream().getReader();
secondStream.read()
.then(({
value
}) => {
return new Response(value, {
headers: {
"Content-Type": "text/html"
}
});
})
.then(response => response.text())
.then(text => {
console.log(text);
});
这似乎是有道理的,因为它立即读取所有内容,而不考虑流是否完成。
我使用过的资源:
https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#Examples https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#Examples
https://philipwalton.com/articles/smaller-html-payloads-with-service-workers/ https://philipwalton.com/articles/smaller-html-payloads-with-service-workers/