export default class RequestQuene { constructor(limits = 10, duration = 200) { this.duration = duration this.limits = limits this.q = [] this.intervalId = null this.intervalDuration = duration this.numOfRunning = 0 } check = () => { if (this.numOfRunning < this.limits) { this.q.splice(0, this.limits - this.numOfRunning).forEach(run => run()) if (this.q.length === 0 && this.intervalId) { clearInterval(this.intervalId) this.intervalId = null } } } enquene(run) { this.q.push(run) if (!this.intervalId) { this.intervalId = setInterval(this.check, this.intervalDuration) } } add(request) { return new Promise((resolve, reject) => { const run = () => { this.numOfRunning++ try { request() .then(res => { resolve(res) }, err => { reject(err) }) .finally(() => { this.numOfRunning-- }) } catch (e) { this.numOfRunning-- reject(e) } } if (this.numOfRunning < this.limits) { run() } else { this.enquene(run) } }) } }