Skip to content

在 Bun 中,Response 對象可以接受異步生成器函數作為其 body。這允許你在數據可用時流式傳輸到客戶端,而無需等待整個響應准備就緒。

ts
Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response(
      // 異步生成器函數
      async function* () {
        yield "Hello, ";
        await Bun.sleep(100);
        yield "world!";

        // 你也可以 yield TypedArray 或 Buffer
        yield new Uint8Array(["\n".charCodeAt(0)]);
      },
      { headers: { "Content-Type": "text/plain" } },
    );
  },
});

你可以直接將任何異步可迭代對象傳遞給 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" } },
    );
  },
});

Bun學習網由www.bunjs.com.cn整理維護