Created
July 25, 2024 07:08
-
-
Save erdesigns-eu/36c6dde59465037546599e43635e17b6 to your computer and use it in GitHub Desktop.
Limit the number of concurrent promises
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
/** | |
* Limit the number of concurrent promises | |
* @param promises The array of promise functions to execute | |
* @param maxConcurrent The maximum number of promises to execute concurrently | |
* @returns A promise that resolves with an array of results | |
*/ | |
export const limitConcurrentPromises = async <T>(promises: (() => Promise<T>)[], maxConcurrent: number): Promise<T[]> => { | |
// Array to store the results of each promise | |
const results: T[] = []; | |
// Array to keep track of the currently executing promises | |
const executing: Set<Promise<void>> = new Set(); | |
// Function to add a promises and manage concurrency | |
const enqueue = async(p: () => Promise<T>): Promise<void> => { | |
// Invoke the promises function and handle the promise it returns | |
const promise = p() | |
.then((result) => { | |
// Push the result to the results array when the promise resolves | |
results.push(result); | |
}) | |
.finally(() => { | |
// Remove the resolved promise from the executing set | |
executing.delete(promise); | |
}); | |
// Add the promise to the executing set | |
executing.add(promise); | |
// If the number of executing promises reaches the maximum concurrency limit | |
if (executing.size >= maxConcurrent) { | |
// Wait for the first promise to resolve | |
await Promise.race(executing); | |
} | |
}; | |
// Iterate over each promise function and enqueue them | |
for (const promise of promises) { | |
await enqueue(promise); | |
} | |
// Wait for all remaining promises to complete | |
await Promise.all(executing); | |
// Return the array of results | |
return results; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment