Created
January 23, 2021 13:03
-
-
Save ValeriiVasin/b0b0c568feb75cc0cf14a37e0564cb3e to your computer and use it in GitHub Desktop.
Revisions
-
ValeriiVasin created this gist
Jan 23, 2021 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,45 @@ 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; }