Last active
November 18, 2021 19:53
-
-
Save jsCommander/3bc3ce90c0ca52d2dc07b74aa63a9011 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
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