Created
June 25, 2019 22:15
-
-
Save mkulke/ab586a1e7990e01be0196842fbfd034c to your computer and use it in GitHub Desktop.
limit concurrency of promises
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
async function limitConcurrency<T, U>( | |
arr: T[], | |
fn: (t: T) => Promise<U>, | |
limit: number, | |
): Promise<U[]> { | |
const results: Promise<U>[] = []; | |
const pool: Promise<void>[] = []; | |
for (const elem of arr) { | |
// add promise to the pool | |
const promise = fn(elem); | |
const running = promise.then(() => { | |
const index = pool.indexOf(running); | |
pool.splice(index, 1); | |
}); | |
pool.push(running); | |
results.push(promise); | |
// if the pool is not full continue | |
if (pool.length < limit) { | |
continue; | |
} | |
// wait for one promise in the pool to resolve | |
await Promise.race(pool); | |
} | |
return Promise.all(results); | |
} | |
const timeout = (i: number) => | |
new Promise(resolve => { | |
setTimeout(() => resolve(i), i); | |
}); | |
async function main(): Promise<void> { | |
await limitConcurrency( | |
[100, 500, 300, 200, 1000, 200, 300, 50, 100, 120, 1232, 500], | |
timeout, | |
4, | |
); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment