Skip to content

Instantly share code, notes, and snippets.

@ValeriiVasin
Created January 23, 2021 13:03
Show Gist options
  • Save ValeriiVasin/b0b0c568feb75cc0cf14a37e0564cb3e to your computer and use it in GitHub Desktop.
Save ValeriiVasin/b0b0c568feb75cc0cf14a37e0564cb3e to your computer and use it in GitHub Desktop.
Parallel execution of multiple async functions
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