Created
June 7, 2021 09:22
-
-
Save iahu/28945f964c8d16fce6601283b0656068 to your computer and use it in GitHub Desktop.
promise throttle
This file contains 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
type Job<T> = () => Promise<T> | |
export const promiseThrottle = async <T>( | |
jobs: Job<T>[], | |
parallelCount: number, | |
onParallelDone?: (results: T[], index: number) => void | |
): Promise<T[]> => { | |
if (!(jobs && Array.isArray(jobs))) { | |
return Promise.reject('jobs must be Array') | |
} | |
let result = [] as T[] | |
for (let i = 0; i < jobs.length; i += parallelCount) { | |
const parallelJobs = jobs.slice(i, i + parallelCount) | |
result = await Promise.all(parallelJobs.map((j) => j())) | |
onParallelDone?.(result, i) | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment