Skip to main content
在 Bun 中,Response 对象可以接受异步生成器函数作为其主体。这允许你在数据可用时将其流式传输到客户端,而无需等待整个响应准备完毕。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79stream-iterator.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
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79stream-iterator.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" } },
    );
  },
});