在 Bun 中,Response 对象可以接受异步生成器函数作为其 body。这允许您在数据可用时将其流式传输给客户端,而不是等待整个响应准备就绪。
Bun.serve({
port: 3000,
fetch(req) {
return new Response(
// An async generator function
async function* () {
yield "Hello, ";
await Bun.sleep(100);
yield "world!";
// you can also yield a TypedArray or Buffer
yield new Uint8Array(["\n".charCodeAt(0)]);
},
{ headers: { "Content-Type": "text/plain" } },
);
},
});
您可以直接将任何异步可迭代对象传递给 Response。
Bun.serve({
port: 3000,
fetch(req) {
return new Response(
{
[Symbol.asyncIterator]: async function* () {
yield "Hello, ";
await Bun.sleep(100);
yield "world!";
},
},
{ headers: { "Content-Type": "text/plain" } },
);
},
});