Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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过来格式就乱了


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...