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 justsml/d48c16e2301789db2aad08d7af39e119 to your computer and use it in GitHub Desktop.
Save justsml/d48c16e2301789db2aad08d7af39e119 to your computer and use it in GitHub Desktop.
Examples of using for-await-of syntax to consume streams.
export const batchStream = (size: number) =>
async function* batchStream<TStreamType>(stream: AsyncIterable<TStreamType>) {
let buffer: TStreamType[] = [];
for await (const chunk of stream) {
buffer.push(chunk);
if (buffer.length >= size) {
yield buffer;
buffer = [];
}
}
if (buffer.length > 0) yield buffer;
buffer = [];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment