带有并发限制的异步调度器
tip
考察event loop
的高级用法
一、题意
JS实现一个带有并发限制的异步调度器Scheduler,保证同时运行的任务最多有十个,完善代码中Scheduler类:
Class Scheduler{
constructor(max){}
run(callback){/*...*/}
}
let s = new Scheduler(10);
s.run(async () => {
/* some async operations */
});
s.run(async () => {
/* some async operations */
});
s.run(async () => {
/* some async operations */
});
二、解法
Class Scheduler{
COUNT = 0; // 记录调试器接收的执行任务个数
LIST = []; // 记录resolve方法
constructor(max){
this.LIMIT = max;
}
async run(callback){
if(this.COUNT >= this.LIMIT){
// 通过await,只要不resolve,代码运行就会阻塞在这里
await new Promise((resolve) => {
this.LIST.push(resolve);
});
}
this.COUNT++;
const result = await callback();
this.COUNT--;
if(this.LIST.length > 0){
this.LIST.shift()(); // 解锁代码阻塞 (注意是双括号,目的是执行resolve())
}
return result;
}
}
let s = new Scheduler(10);
s.run(async () => {
/* some async operations */
});
s.run(async () => {
/* some async operations */
});
s.run(async () => {
/* some async operations */
});