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.

Revisions

  1. ValeriiVasin created this gist Jan 23, 2021.
    45 changes: 45 additions & 0 deletions parallel-by.ts
    Original 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;
    }