修改 Scheduler 类 add 方法,维护最大并发为两个
class Scheduler {
async add(promiseFunc: () => Promise<void>): Promise<void> {}
}
const scheduler = new Scheduler();
const timeout = (time) => {
return new Promise((r) => setTimeout(r, time));
};
const addTask = (time, order) => {
scheduler.add(() => timeout(time)).then(() => console.log(order));
};
addTask(1000, 1);
addTask(500, 2);
addTask(300, 3);
addTask(400, 4); // log: 2 3 1 4