异步调度任务,同一时间限制输出。
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) { 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);
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}`) });
|