Last active
July 3, 2026 23:12
-
-
Save theMackabu/7142d760a1939f962b6df4f00ec2511d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| async function* poolResults(items, concurrency, worker) { | |
| const it = items[Symbol.iterator](); | |
| const buffer = []; | |
| let active = 0; | |
| let wake = null; | |
| const signal = () => { | |
| if (wake) { | |
| const w = wake; | |
| wake = null; | |
| w(); | |
| } | |
| }; | |
| const launch = () => { | |
| const next = it.next(); | |
| if (next.done) return; | |
| active++; | |
| Promise.resolve(worker(next.value)) | |
| .then(value => buffer.push({ value })) | |
| .catch(error => buffer.push({ error })) | |
| .finally(() => { | |
| active--; | |
| launch(); | |
| signal(); | |
| }); | |
| }; | |
| for (let i = 0; i < concurrency; i++) launch(); | |
| while (active > 0 || buffer.length > 0) { | |
| if (buffer.length === 0) { | |
| await new Promise(r => (wake = r)); | |
| continue; | |
| } | |
| const { value, error } = buffer.shift(); | |
| if (error) throw error; | |
| yield value; | |
| } | |
| } |
This file contains hidden or 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
| async function pool<T>(items: T[], concurrency: number, worker: (x: T) => Promise<void>) { | |
| let i = 0; | |
| const run = async () => { | |
| while (i < items.length) { | |
| await worker(items[i++]); | |
| } | |
| }; | |
| await Promise.all(Array.from({ length: concurrency }, run)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment