Skip to content

En Bun, los objetos Response pueden aceptar una función generadora asíncrona como su cuerpo. Esto te permite transmitir datos al cliente a medida que están disponibles, en lugar de esperar a que toda la respuesta esté lista.

ts
Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response(
      // Una función generadora asíncrona
      async function* () {
        yield "Hello, ";
        await Bun.sleep(100);
        yield "world!";

        // también puedes hacer yield de un TypedArray o Buffer
        yield new Uint8Array(["\n".charCodeAt(0)]);
      },
      { headers: { "Content-Type": "text/plain" } },
    );
  },
});

---

Puedes pasar cualquier iterable asíncrono directamente a `Response`:

```ts stream-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" } },
    );
  },
});

Bun por www.bunjs.com.cn editar