Implement an asynchronous Scheduler Scheduler with concurrency limits that allow up to two tasks to run simultaneously

1. The async version

Class Scheduler {constructor(maxNum) {// this. TaskList = [] // Number of current tasks this This.maxnum = maxNum} async add(promiseCreator) {if (this.count >= this.maxnum) {await new Promise(resolve => { this.taskList.push(resolve) }) } this.count++ const result = await promiseCreator() If (this.tasklist.length > 0) {this.taskList.shift()()} return result}} if (this.tasklist.length > 0) {this.taskList.shift()()} return result}} const timeout = time => { return new Promise(resolve => { setTimeout(resolve, time) }) } const scheduler = new Scheduler(2) const addTask = (time, value) => { scheduler.add(() => { return timeout(time).then(() => { console.log(value) }) }) } addTask(1000, "1") addTask(500, "2") addTask(300, "3") addTask(400, "4") addTask(300, "3") addTask(400, "4") Task 3 enters the queue // at 800ms, 3 is completed and 3 is output. Task 4 enters the queue // at 1000ms, 1 is completed and 1 is output // at 1200ms, 4 is completed and 4 is outputCopy the code

2. Promise

Class Scheduler {constructor(maxNum) {// constructor = [] this.tasklist = [] this.handlelist = [] this.handlelist = [] This. MaxNum = maxNum} run(promiseCreator) {this.count++ return promiseCreator().then((res) => { this.count-- if (this.handleList.length) this.handleList.shift()(); Return res})} add(promiseCreator) {if (this.count >= this.maxNum) {const promise = new  Promise((resolve) => this.handleList.push(resolve)) this.taskList.push(promise) } if (this.taskList.length) { return this.taskList.shift().then(() => this.run(promiseCreator)) } return this.run(promiseCreator) } } const timeout = time =>  { return new Promise(resolve => { setTimeout(resolve, time) }) } const scheduler = new Scheduler(2) const addTask = (time, value) => { scheduler.add(() => { return timeout(time).then(() => { console.log(value) }) }) } addTask(1000, "1") addTask(500, "2") addTask(300, "3") addTask(400, "4")Copy the code

3. Promise Lite

Class Scheduler {constructor(maxNum) {// this. TaskList = [] // Number of current tasks this this.maxNum = maxNum } run() { this.count++ this.taskList.shift()().then((result) => { this.count-- if(this.taskList.length) this.run() }) } add(promiseCreator) { this.taskList.push(() => promiseCreator()) This.count < this.maxnum && this.run()}}Copy the code