• 3.9k

一道前端控制异步流的题,求解

修改 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
阅读 153
评论
    1 个回答
    • 4.8k
    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过来格式就乱了

      撰写回答

      登录后参与交流、获取后续更新提醒

      相似问题
      推荐文章