Last active
March 23, 2021 13:18
-
-
Save kessler/3102c548f3fae13856c1aec12cc13955 to your computer and use it in GitHub Desktop.
consume browser readable stream as async iterator
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 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