Created
July 4, 2022 22:32
-
-
Save natevw/79e04dba0cda6c87e19eb63a6a4986ba to your computer and use it in GitHub Desktop.
Revisions
-
natevw created this gist
Jul 4, 2022 .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,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; } } }