Last active
May 2, 2020 10:36
-
-
Save tranquan/8c14fd6893385648dc5b295f94880744 to your computer and use it in GitHub Desktop.
Run promise all with limit how many task can run in concurrence
This file contains hidden or 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
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