Skip to content

Instantly share code, notes, and snippets.

@murooka
Created January 12, 2022 09:27
Show Gist options
  • Select an option

  • Save murooka/7d87c06246ca66468fd9a56aaa03783d to your computer and use it in GitHub Desktop.

Select an option

Save murooka/7d87c06246ca66468fd9a56aaa03783d to your computer and use it in GitHub Desktop.
async function* generate(count) {
for (let i = 1; i <= count; i++) {
await new Promise((resolve) => setTimeout(resolve, 1000));
yield i;
}
}
async function* chunkAsync(iterator, size) {
let items = [];
for await (const item of iterator) {
items.push(item);
if (items.length >= size) {
yield items;
items = [];
}
}
if (items.length > 0) yield items;
}
const main = async () => {
const begin = Date.now();
for await (const item of chunkAsync(generate(10), 2)) {
console.log(Date.now() - begin, item);
}
};
main()
.then(() => process.exit(0))
.catch((err) => {
console.error(err);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment