Skip to content

Instantly share code, notes, and snippets.

@TorbjornHoltmon
Last active October 1, 2025 19:37
Show Gist options
  • Select an option

  • Save TorbjornHoltmon/59e836519da81852d495b9ecaeaf1fbb to your computer and use it in GitHub Desktop.

Select an option

Save TorbjornHoltmon/59e836519da81852d495b9ecaeaf1fbb to your computer and use it in GitHub Desktop.
Streaming data with async generators
async function returnWait<T>(timeToDelay: number, value: T): Promise<T> {
return new Promise((resolve) => setTimeout(() => resolve(value), 1000));
}
const encoder = new TextEncoder();
async function* iterator() {
let index = 0;
if (index === 0) {
const thing = await returnWait(1000, { hello: 'first' });
yield encoder.encode('[' + JSON.stringify(thing));
++index;
}
while (index !== 1000) {
const thing = await returnWait(1000, { hello: 'middle' });
index++;
if (index === 1000) {
yield encoder.encode(JSON.stringify(thing) + ']');
} else {
yield encoder.encode(JSON.stringify(thing));
}
}
}
const generator = iterator();
const streamResponse = new ReadableStream({
async pull(controller) {
const { value, done } = await generator.next();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
},
});
return new Response(streamResponse, {
status: 200,
headers: {
'Content-Type': 'application/json',
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment