Skip to content

Instantly share code, notes, and snippets.

@jsCommander
Last active November 18, 2021 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsCommander/3bc3ce90c0ca52d2dc07b74aa63a9011 to your computer and use it in GitHub Desktop.
Save jsCommander/3bc3ce90c0ca52d2dc07b74aa63a9011 to your computer and use it in GitHub Desktop.
export async function promiseAllWithLimit<T>(
promiseGenerators: Array<() => Promise<T>>,
poolLimit: number
): Promise<T[]> {
let currentIndex = poolLimit - 1;
const total = promiseGenerators.length;
const results: T[] = Array(total);
const next = async (index: number): Promise<void> => {
if (index >= total) {
return;
}
return promiseGenerators[index]().then((result) => {
results[index] = result;
currentIndex++;
return next(currentIndex);
});
};
const workers = Array(poolLimit)
.fill(null)
.map((_, index) => next(index));
return Promise.all(workers).then(() => results);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment