Created
April 12, 2023 20:23
-
-
Save bigs/32e6f04275016aeb7a9f50c204f5cae0 to your computer and use it in GitHub Desktop.
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
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