Skip to content

Instantly share code, notes, and snippets.

@bigs
Created April 12, 2023 20:23
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 bigs/32e6f04275016aeb7a9f50c204f5cae0 to your computer and use it in GitHub Desktop.
Save bigs/32e6f04275016aeb7a9f50c204f5cae0 to your computer and use it in GitHub Desktop.
const CHUNK_SIZE = 50;
class FetchUsers implements AsyncIterable<string> {
#users: string[];
#chunk: number;
constructor() {
this.#chunk = 0;
this.#users = [];
}
#generateChunk() {
if (this.#chunk >= 5) {
this.#users = [];
return;
}
this.#users = new Array(CHUNK_SIZE);
for (let i = 0; i < CHUNK_SIZE; i++) {
const user = `User ${i + (this.#chunk * CHUNK_SIZE)}`;
this.#users[i] = user;
}
this.#chunk += 1;
}
[Symbol.asyncIterator]() {
const self = this;
return {
async next(value?: any): Promise<IteratorResult<string>> {
if (!self.#users.length) {
self.#generateChunk();
}
const user = self.#users.shift();
if (user === undefined) {
return { done: true, value: null };
}
return { done: false, value: user };
}
}
}
}
async function main() {
const users = new FetchUsers();
for await (const user of users) {
console.log(`Got user: ${user}`);
}
}
main().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment