promisedip
Version:
Promise pooler to manage concurrency
2 lines (1 loc) • 1.1 kB
JavaScript
!function(t,s){"object"==typeof exports&&"undefined"!=typeof module?module.exports=s():"function"==typeof define&&define.amd?define(s):(t="undefined"!=typeof globalThis?globalThis:t||self).PromisePool=s()}(this,(function(){"use strict";class t{constructor({concurrency:t}){const s=t=>{throw new Error("concurrency must be "+t)};Number.isFinite(t)||s("finite"),Number.isInteger(t)||s("an integer"),t<1&&s("greater than 0"),this.t=[],this.i=0,this.o=t,this.h=[]}static async map(s,e,n){const i=new t(n);return Promise.all([...s].map((async(t,s,n)=>i.resolve((async()=>e(t,s,n))))))}async resolve(t){const s=this.u(t);return this.t.push(t),1===this.t.length&&this.l(),s}m(t,s){const e=[];this.h.forEach((n=>{n(t,s)&&e.push(n)})),this.h=this.h.filter((t=>!e.includes(t)))}p(t){this.h.push(t)}async u(t){return new Promise((s=>{this.p(((e,n)=>e===t&&(s(n),!0)))}))}async _(){return new Promise((t=>{this.p((()=>(t(),!0)))}))}async l(){for(;this.t.length>0;){for(;this.i>=this.o;)await this._();const t=this.t.shift(),s=t();this.i+=1;const e=()=>{this.m(t,s),this.i-=1};s.then(e,e).catch(e)}}}return t}));