Last active
June 4, 2024 10:44
-
-
Save TorbjornHoltmon/59e836519da81852d495b9ecaeaf1fbb to your computer and use it in GitHub Desktop.
Streaming data with async generators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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