实现最大并发数是2的类
2023-11-06 17:27
字节面试的最后一题,给了 5 分钟,有点匆忙,没写出来,结束后花时间再看了下, 几分钟就做出来了。
当时主要问题是,调用方要返回一个 promise,处理起来有点复杂,后来发现,绑定 resolve 和要执行的异步函数,然后每个异步函数执行完执行对应的 resolve, 就可以了。
具体代码:
class Scheduler {
maxCnt = 2;
constructor() {
this.cnt = 0;
this.arr = [];
}
add(promiseCreator) {
return new Promise((resolve, reject) => {
if (this.cnt < this.maxCnt) {
this.execute(promiseCreator, resolve);
} else {
this.arr.push([promiseCreator, resolve]);
}
});
}
execute(fn, resolve) {
this.cnt++;
fn().then(() => {
this.cnt--;
resolve();
if (this.arr.length) {
const [fn, res] = this.arr.shift();
this.execute(fn, res);
}
});
}
}
const timeout = (time) =>
new Promise((resolve) => {
setTimeout(resolve, time);
});
const scheduler = new Scheduler();
const addTask = (time, order) => {
scheduler.add(() => timeout(time)).then(() => console.log(order));
};
addTask(4000, 4);
addTask(2000, 2);
addTask(3000, 3);
addTask(1000, 1);