异步调度任务,同一时间限制输出。

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Scheduler {
list = [];

count = 0;

constructor(num) {
this.num = num;
}

async add(fn) {//fn是一个异步函数,返回
if (this.count >= this.num) {
await new Promise((resolve) => {
this.list.push(resolve);
});
}

this.count++;

let res = await fn();

this.count--;

if (this.list.length > 0) {
this.list.shift()();
}

return res;
}
}

//以下是调用执行
const schedule = new Scheduler(2);//最多同一时间让它执行3个异步函数

const asyncFacotory = (n, time) => {

return () => {

return new Promise((resolve) => {

setTimeout(() => {
resolve(n);
}, time)

})

}

}

schedule.add(asyncFacotory(1, 2000)).then((n) => {
console.log(`异步任务:${n}`)
});
schedule.add(asyncFacotory(2, 2000)).then((n) => {
console.log(`异步任务:${n}`)
});
schedule.add(asyncFacotory(3, 2000)).then((n) => {
console.log(`异步任务:${n}`)
});
schedule.add(asyncFacotory(4, 2000)).then((n) => {
console.log(`异步任务:${n}`)
});
schedule.add(asyncFacotory(5, 2000)).then((n) => {
console.log(`异步任务:${n}`)
});
schedule.add(asyncFacotory(6, 2000)).then((n) => {
console.log(`异步任务:${n}`)
});

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!