Created
February 17, 2023 08:39
-
-
Save timneutkens/ad0da756d522684d91eda6f6f6069aeb to your computer and use it in GitHub Desktop.
Streaming example
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
// https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#convert_async_iterator_to_stream | |
function iteratorToStream(iterator: any) { | |
return new ReadableStream({ | |
async pull(controller) { | |
const { value, done } = await iterator.next() | |
if (done) { | |
controller.close() | |
} else { | |
controller.enqueue(value) | |
} | |
}, | |
}) | |
} | |
function sleep(time) { | |
return new Promise((resolve) => { | |
setTimeout(resolve, time) | |
}) | |
} | |
const encoder = new TextEncoder() | |
async function* makeIterator() { | |
yield encoder.encode('<p>one</p>') | |
await sleep(200) | |
yield encoder.encode('<p>two</p>') | |
await sleep(200) | |
yield encoder.encode('<p>three</p>') | |
} | |
export async function GET() { | |
const iterator = makeIterator() | |
const stream = iteratorToStream(iterator) | |
return new Response(stream) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment