Topic:

JavaScript implements an asynchronous Scheduler with concurrency limits, guaranteeing up to two tasks to run at the same time. Refine the Scheduler class in the code so that the following programs output correctly.

Points to note:

  • Add has a dot then so add is a Promise object

Implementation steps:

  1. Because we have a. Then after the add function, we need a return Promise inside the add function

  2. We need to create two lists, Tasks and usingTask. UsingTask is a queue of tasks that are being executed, up to two. Taks are queues of tasks waiting to be executed

  3. After we return the Promise in the add function, we need to add resolve to the current function promiseCreator, which is used to break the Promise out of the then function after execution

  4. The previous step is to check whether the length of the usingTask is less than 2. If the length is less than 2, the task is added to the usingTask queue and executed directly. If the value is greater than 2, it is added to the Tasks queue

  5. Once we add it to usingTask, we can execute it directly, and once we’ve executed it, in the then method, we need to do three things

  6. We start with promisecreator.resolve () because we return a Promise object, so resolve is required

  7. Now that it is done, there is no need to delete it before it occupies the usingTask’s place

  8. Finally, the tasks in the Tasks are added to the usingTask and executed. Since it’s a queue, we need to call the Shift method

Implementation code:

Class Scheduler {constructor() {this.tasks = [], // usingTask = [] // running tasks} // return Promise add(promiseCreator) { return new Promise((resolve, reject) => { promiseCreator.resolve = resolve if (this.usingTask.length < 2) { this.usingRun(promiseCreator) } else { this.tasks.push(promiseCreator) } }) } usingRun(promiseCreator) { this.usingTask.push(promiseCreator) promiseCreator().then(() => { promiseCreator.resolve() let index = this.usingTask.findIndex(promiseCreator) this.usingTask.splice(index, 1) if (this.tasks.length > 0) { this.usingRun(this.tasks.shift()) } }) } } 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(400, 4) addTask(200, 2) addTask(300, 3) addTask(100, 1) // 2, 4, 3, 1Copy the code