In Bun, gli oggetti Response possono accettare una funzione generatore asincrona come loro corpo. Questo ti consente di streamare dati al client man mano che diventano disponibili, invece di aspettare che l'intera risposta sia pronta.
ts
Bun.serve({
port: 3000,
fetch(req) {
return new Response(
// Una funzione generatore asincrona
async function* () {
yield "Ciao, ";
await Bun.sleep(100);
yield "mondo!";
// puoi anche yieldare un TypedArray o Buffer
yield new Uint8Array(["\n".charCodeAt(0)]);
},
{ headers: { "Content-Type": "text/plain" } },
);
},
});Puoi passare qualsiasi iterabile asincrono direttamente a Response:
ts
Bun.serve({
port: 3000,
fetch(req) {
return new Response(
{
[Symbol.asyncIterator]: async function* () {
yield "Ciao, ";
await Bun.sleep(100);
yield "mondo!";
},
},
{ headers: { "Content-Type": "text/plain" } },
);
},
});