Skip to content

Instantly share code, notes, and snippets.

@iahu
Created June 7, 2021 09:22
Show Gist options
  • Save iahu/28945f964c8d16fce6601283b0656068 to your computer and use it in GitHub Desktop.
Save iahu/28945f964c8d16fce6601283b0656068 to your computer and use it in GitHub Desktop.
promise throttle
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