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

fish
  • 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
回复
阅读 363
1 个回答
✓ 已被采纳
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过来格式就乱了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏