JS 实现一个带并发限制的异步调度器Scheduler,保证同时运行的任务最多有两个。完善代码中Scheduler类,使得以下程序能正确输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Scheduler {
add(promiseCreator) {
/* ... */
}
// ...
}

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(1000, "1");
addTask(500, "2");
addTask(300, "3");
addTask(400, "4");

// output: 2 3 1 4
// 一开始,1、2两个任务进入队列
// 500ms时,2完成,输出2,任务3进队
// 800ms时,3完成,输出3,任务4进队
// 1000ms时,1完成,输出1
// 1200ms时,4完成,输出4

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Scheduler {
constructor() {
this.unwork = [];
this.count = 0;
}

add(promiseCreator) {
return new Promise((resolve) => {
promiseCreator.resolve = resolve;
if (this.count < 2) {
this.runTask(promiseCreator);
} else {
this.unwork.push(promiseCreator);
}
});
}

runTask(promiseCreator) {
this.count++;
promiseCreator().then(() => {
promiseCreator.resolve();
this.count--;
if (this.unwork.length > 0) {
const newTask = this.unwork.shift();
this.runTask(newTask);
}
});
}
}