Skip to content

Instantly share code, notes, and snippets.

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 kessler/3102c548f3fae13856c1aec12cc13955 to your computer and use it in GitHub Desktop.
Save kessler/3102c548f3fae13856c1aec12cc13955 to your computer and use it in GitHub Desktop.
consume browser readable stream as async iterator
async function main() {
const { body } = await fetch('https://jsonplaceholder.typicode.com/photos')
const streamIterator = new StreamChunkIterator(body.getReader())
for await (const chunk of streamIterator) {
console.log(chunk)
}
console.log('Voilà!')
}
// you can probably make this code thinner
// maybe dump the getters or not make it a class at all
class StreamChunkIterator {
constructor(reader) {
this._reader = reader
this._decoder = new TextDecoder('utf-8')
}
get value() {
return this._value
}
get done() {
return this._done
}
async next() {
const { value, done } = await this._reader.read()
if (!done) {
this._value = this._decoder.decode(value, { stream: true })
}
this._done = done
return this
}
[Symbol.asyncIterator] () {
return this
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment