Skip to content

Instantly share code, notes, and snippets.

@natevw
Created July 4, 2022 22:32
Show Gist options
  • Select an option

  • Save natevw/79e04dba0cda6c87e19eb63a6a4986ba to your computer and use it in GitHub Desktop.

Select an option

Save natevw/79e04dba0cda6c87e19eb63a6a4986ba to your computer and use it in GitHub Desktop.

Revisions

  1. natevw created this gist Jul 4, 2022.
    51 changes: 51 additions & 0 deletions Politer.mjs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    /*
    import Politer from "./this_gist.mjs";
    let q = Politer(2),
    politelyFetch = q.wrap(fetch);
    Promise.all([
    politelyFetch(req1),
    politelyFetch(req2),
    politelyFetch(req3),
    politelyFetch(req4),
    politelyFetch(req5),
    ]).then(/* … */);

    */

    export default class PromiseLimiter {
    constructor(n) {
    this._max = n;
    this._wip = 0;
    this._q = [];
    }

    _proceedIfReady() {
    if (this._q.length && this._wip < this._max) {
    ++this._wip;
    let task = this._q.pop();
    task.fn.apply(task.ctx, task.args)
    .then(result => { task.resolve(result); })
    .catch(error => { task.reject(error); })
    .finally(() => {
    --this._wip;
    this._proceedIfReady();
    });
    }
    }

    wrap(fn) {
    let scope = this;
    return function () {
    let task = {fn, ctx:this, args:arguments};
    let asyncResult = new Promise((resolve, reject) => {
    Object.assign(task, {resolve,reject});
    });
    scope._q.unshift(task);
    scope._proceedIfReady();
    return asyncResult;
    }
    }
    }