Created
October 12, 2020 09:02
-
-
Save qwtel/d2d2ec67ab2c626008bac36e0507a3ef to your computer and use it in GitHub Desktop.
Convert WHATWG web streams to async iterables and back
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
export async function* streamToAsyncIterable<T>(stream: ReadableStream<T>): AsyncIterableIterator<T> { | |
const reader = stream.getReader(); | |
try { | |
while (true) { | |
const { done, value } = await reader.read(); | |
if (done) return; | |
yield value; | |
} | |
} finally { reader.releaseLock() } | |
} | |
export function asyncIterableToStream<T>(asyncIterable: AsyncIterable<T>): ReadableStream<T> { | |
const { readable, writable } = new TransformStream<T, T>(); | |
(async () => { | |
const writer = writable.getWriter(); | |
try { | |
for await (const x of asyncIterable) writer.write(x); | |
} finally { writer.close() } | |
})(); | |
return readable; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment