Skip to content

Instantly share code, notes, and snippets.

@pennane
Last active July 15, 2024 07:48
Show Gist options
  • Select an option

  • Save pennane/21442a0021cb7db53e74cad09354d17d to your computer and use it in GitHub Desktop.

Select an option

Save pennane/21442a0021cb7db53e74cad09354d17d to your computer and use it in GitHub Desktop.
function promiseAllLimitedConcurrency<A, B>(
maxConcurrency: number,
f: (x: A) => Promise<B>,
xs: A[]
): Promise<
[
fulfilledValues: Array<PromiseFulfilledResult<B>['value']>,
rejectedReasons: Array<PromiseRejectedResult['reason']>
]
> {
return new Promise(resolve => {
const values: B[] = [];
const reasons: any[] = [];
const total = xs.length;
let completed = 0;
let started = 0;
function next() {
if (completed >= total) {
return resolve([values, reasons] as const);
}
if (started < total) {
const index = started;
started++;
void f(xs[index])
.then(value => ({ status: 'fulfilled' as const, value }))
.catch(reason => ({ status: 'rejected' as const, reason }))
.then(result => {
completed++;
if (result.status === 'fulfilled') {
values.push(result.value);
} else {
reasons.push(result.status);
}
next();
});
}
}
for (let i = 0; i < Math.min(maxConcurrency, total); i++) next()
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment