Created
January 23, 2021 13:03
-
-
Save ValeriiVasin/b0b0c568feb75cc0cf14a37e0564cb3e to your computer and use it in GitHub Desktop.
Parallel execution of multiple async functions
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 parallelBy( | |
fns: Array<() => Promise<any>>, | |
limit: number | |
) { | |
let resolved = 0; | |
let flying: Array<Promise<any>> = []; | |
const results = Array(fns.length); | |
let done = false; | |
if (limit >= fns.length) { | |
return Promise.all(fns.map((fn) => fn())); | |
} | |
function exec(index: number) { | |
const fn = fns[index]; | |
const promise = fn(); | |
flying.push(promise); | |
promise | |
.then((result) => { | |
results[index] = result; | |
flying = flying.filter((p) => p !== promise); | |
resolved += 1; | |
done = resolved === fns.length; | |
}) | |
.catch((reason) => { | |
throw reason; | |
}); | |
} | |
let index = 0; | |
while (index < limit) { | |
exec(index); | |
index++; | |
} | |
while (!done && index < fns.length) { | |
await Promise.race(flying); | |
exec(index); | |
index++; | |
} | |
await Promise.all(flying); | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment