class Scheduler{
constructor(max) {
this.max = max
this.queue = []
this.count = 0
}
async add (promise) {
if (this.count>=this.max) {
await new Promise((resolve)=>{this.queue.push(resolve)})
}
this.count++
const res = await promise()
this.count--
if (this.queue.length) {
this.queue.shift()()
}
return res
}
}
const scheduler2 = new Scheduler(2)
const addTask = (ms, data) => {
scheduler2
.add(()=>new Promise(resolve => {
setTimeout(() => {
resolve(data)
}, ms);
}))
.then(e => console.log(e))
}
addTask(1000, '1')
addTask(500, '2')
addTask(300, '3')
addTask(400, '4')