Skip to content

Instantly share code, notes, and snippets.

@TorbjornHoltmon
Last active December 20, 2023 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TorbjornHoltmon/59e836519da81852d495b9ecaeaf1fbb to your computer and use it in GitHub Desktop.
Save TorbjornHoltmon/59e836519da81852d495b9ecaeaf1fbb to your computer and use it in GitHub Desktop.
Streaming data with async generators
async function returnWait<T>(timeToDelay: number, returnValue: T): Promise<T> {
return new Promise((resolve) => setTimeout(() => resolve(returnValue), timeToDelay));
}
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