Skip to content

Instantly share code, notes, and snippets.

@timneutkens
Created February 17, 2023 08:39
Show Gist options
  • Save timneutkens/ad0da756d522684d91eda6f6f6069aeb to your computer and use it in GitHub Desktop.
Save timneutkens/ad0da756d522684d91eda6f6f6069aeb to your computer and use it in GitHub Desktop.
Streaming example
// 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