class Scheduler {
constructor(maxNum) {
this.taskList = [];
this.count = 0;
this.maxNum = maxNum;
}
async add(promiseCreator) {
if (this.count >= this.maxNum) {
await new Promise((resolve) => {
this.taskList.push(resolve)
})
}
this.count ++;
const result = await promiseCreator();
this.count --;
if (this.taskList.length > 0) {
this.taskList.shift()();
}
return result;
}
}
const timeout = (time) => new Promise(resolve => {
setTimeout(resolve, time)
})
const scheduler = new Scheduler(2);
const addTask = (time, val) => {
scheduler.add(() => {
return timeout(time).then(() => {
console.log(val)
})
})
}
addTask(1000, '1');
addTask(500, '2');
addTask(300, '3');
addTask(400, '4');
//2314
类Scheduler中的add方法中的第一句,通过await阻塞Promise但是又不执行resolve,而是将resolve保存到数组当中去,这样就达到了当异步任务超过maxNum个时线程就会阻塞在第一行.每执行完一个异步任务就会去数组中查看一下有没有还处于阻塞当中的异步任务,如果有的话就执行最前面的那个异步任务.