Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【2021-07-8~2021-07-9】实现有并行限制的 Promise 调度器 #3

Open
superDCH opened this issue Jul 9, 2021 · 1 comment

Comments

@superDCH
Copy link
Owner

superDCH commented Jul 9, 2021

JS实现一个带并发限制的异步调度器Scheduler,保证同时运行的任务最多有两个。完善下面代码的Scheduler类,使以下程序能够正常输出:

class Scheduler {
  add(promiseCreator) { ... }
  // ...
}
   
const timeout = time => new Promise(resolve => {
  setTimeout(resolve, time);
})
  
const scheduler = new Scheduler();
  
const addTask = (time,order) => {
  scheduler.add(() => timeout(time).then(()=>console.log(order)))
}

addTask(1000, '1');
addTask(500, '2');
addTask(300, '3');
addTask(400, '4');

// output: 2 3 1 4
@superDCH
Copy link
Owner Author

superDCH commented Jul 9, 2021

class Scheduler {
  constructor(){
    this.maxCount=2
    this.currentCount=0
    this.taskList=[]
  }
  add(promiseCreator) { 
    if(typeof promiseCreator !== 'function') return false
    this.taskList.push(promiseCreator)
    this.runTask()
  }
  runTask(){
    let restCount=this.maxCount-this.currentCount
    for(let i=0;i<restCount;i++){
      if(this.taskList.length === 0) return
      let taskItem=this.taskList.shift()
      taskItem().then(()=>{
        this.currentCount--
        this.runTask()
      })
      this.currentCount++
    }
  }
}

@superDCH superDCH changed the title 【2021-07-9~2021-07-10】实现有并行限制的 Promise 调度器 【2021-07-8~2021-07-9】实现有并行限制的 Promise 调度器 Jul 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant