Skip to content

Instantly share code, notes, and snippets.

@tranquan
Last active May 2, 2020 10:36
Show Gist options
  • Save tranquan/8c14fd6893385648dc5b295f94880744 to your computer and use it in GitHub Desktop.
Save tranquan/8c14fd6893385648dc5b295f94880744 to your computer and use it in GitHub Desktop.
Run promise all with limit how many task can run in concurrence
export async function promiseAllLimit<T>(n: number, list: (() => Promise<T>)[]) {
const head = list.slice(0, n);
const tail = list.slice(n);
const result: T[] = [];
const execute = async (promise: () => Promise<T>, i: number, runNext: () => Promise<void>) => {
result[i] = await promise();
await runNext();
};
const runNext = async () => {
const i = list.length - tail.length;
const promise = tail.shift();
if (promise !== undefined) {
await execute(promise, i, runNext);
}
};
await Promise.all(head.map((promise, i) => execute(promise, i, runNext)));
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment