Last active
July 15, 2024 07:48
-
-
Save pennane/21442a0021cb7db53e74cad09354d17d 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
| function promiseAllLimitedConcurrency<A, B>( | |
| maxConcurrency: number, | |
| f: (x: A) => Promise<B>, | |
| xs: A[] | |
| ): Promise< | |
| [ | |
| fulfilledValues: Array<PromiseFulfilledResult<B>['value']>, | |
| rejectedReasons: Array<PromiseRejectedResult['reason']> | |
| ] | |
| > { | |
| return new Promise(resolve => { | |
| const values: B[] = []; | |
| const reasons: any[] = []; | |
| const total = xs.length; | |
| let completed = 0; | |
| let started = 0; | |
| function next() { | |
| if (completed >= total) { | |
| return resolve([values, reasons] as const); | |
| } | |
| if (started < total) { | |
| const index = started; | |
| started++; | |
| void f(xs[index]) | |
| .then(value => ({ status: 'fulfilled' as const, value })) | |
| .catch(reason => ({ status: 'rejected' as const, reason })) | |
| .then(result => { | |
| completed++; | |
| if (result.status === 'fulfilled') { | |
| values.push(result.value); | |
| } else { | |
| reasons.push(result.status); | |
| } | |
| next(); | |
| }); | |
| } | |
| } | |
| for (let i = 0; i < Math.min(maxConcurrency, total); i++) next() | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment