Created
June 16, 2023 01:46
-
-
Save mrsarm/e8094eaf661bdc7c985520bc8568a351 to your computer and use it in GitHub Desktop.
promise-concurrency-limit.ts: Execute concurrently the asynchronous functions passed, with a limit in concurrency
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
/** | |
* Execute concurrently the asynchronous functions `fns` passed, but | |
* not more than `maxConcurrency` at the same time. All functions | |
* return the same type T, an a promise with T[] inside is returned. | |
*/ | |
const execConcurrent = async<T> ( | |
fns: (() => Promise<T>)[], | |
maxConcurrency: number, | |
): Promise<T[]> => { | |
const res: T[] = []; | |
while (fns.length) { | |
const results = await Promise.all( fns.splice(0, maxConcurrency).map(f => f()) ); | |
res.push(...results); | |
} | |
return res; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment