Skip to content

Instantly share code, notes, and snippets.

@qwtel
Created October 12, 2020 09:02
Show Gist options
  • Save qwtel/d2d2ec67ab2c626008bac36e0507a3ef to your computer and use it in GitHub Desktop.
Save qwtel/d2d2ec67ab2c626008bac36e0507a3ef to your computer and use it in GitHub Desktop.
Convert WHATWG web streams to async iterables and back
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