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