Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

修改 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

class Scheduler {
    constructor(){
        this.rtasks = [];
        this.atasks = [];
        this.maxlimit = 2;
 }
    async add(promiseFunc){
        if(this.rtasks.length >= this.maxlimit) {
         return Promise.race(this.rtasks).then(() =>    this.add(promiseFunc))
        }
        let task = promiseFunc();
        this.atasks.push(task);
        let rt = task.then(() =>this.rtasks.splice(this.rtasks.indexOf(rt),1));
        this.rtasks.push(rt);
        return rt;
 }
}
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

吐槽下 ,segmentfalut编辑器不好用,编辑器cp过来格式就乱了


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...