0%

任务队列

实现代码

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
30
31
class Task {
constructor(count) {
this.maxCount = count;
this.runCount = 0;
this.tasks = [];
}

add(task) {
return new Promise((resolve, reject) => {
this.tasks.push({
task,
resolve,
reject,
});
this.run();
});
}

run() {
while (this.tasks.length && this.runCount < this.maxCount) {
const { task, resolve, reject } = this.tasks.shift();
this.runCount++;
task()
.then(resolve, reject)
.finally(() => {
this.runCount--;
this.run();
});
}
}
}

demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const task = new Task(2);
function demo(time, index) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(index);
console.log(index);
}, time);
});
}
// 最多同时执行两个任务 所以这里先打印1,2然后打印3,4
task.add(() => demo(1000, 1));
task.add(() => demo(1000, 2));
task.add(() => demo(1000, 3));
task.add(() => demo(1000, 4));