class PromiseLimit {
_tasks = []
_count = 0
constructor (limit) {
this.limit = limit
}
add (promise) {
return new Promise((resolve, reject) => {
let task = this.createTask(promise, resolve, reject)
if (this._count >= this.limit) {
this._tasks.push(task)
} else {
task()
}
})
}
createTask (promise, resolve, reject) {
return () => {
promise().then(
v => resolve(v),
r => reject(r)
).finally(() => {
this._count--
if (this._tasks.length) {
let task = this._tasks.shift()
task()
}
})
this._count++
}
}
}
console