Bun 에서 Response 객체는 바디로 async generator 함수를 허용합니다. 이를 통해 전체 응답이 준비될 때까지 기다리는 대신 데이터를 사용할 수 있게 되면 클라이언트로 스트리밍할 수 있습니다.
ts
Bun.serve({
port: 3000,
fetch(req) {
return new Response(
// async generator 함수
async function* () {
yield "Hello, ";
await Bun.sleep(100);
yield "world!";
// TypedArray 나 Buffer 도 yield 할 수 있습니다
yield new Uint8Array(["\n".charCodeAt(0)]);
},
{ headers: { "Content-Type": "text/plain" } },
);
},
});어떤 async iterable 도 Response 에 직접 전달할 수 있습니다.
ts
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" } },
);
},
});