Skip to content

Instantly share code, notes, and snippets.

@mrsarm
Created June 16, 2023 01:46
Show Gist options
  • Save mrsarm/e8094eaf661bdc7c985520bc8568a351 to your computer and use it in GitHub Desktop.
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
/**
* 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