The following is a fascinating front end topic that examines the understanding and use of promises:
Implement an asynchronous Scheduler Scheduler with concurrency limits to ensure that up to two tasks run simultaneously. Refine the Scheduler class in the following code so that the following program outputs correctly.
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')
// The printing sequence is: 2, 3, 1, 4
Copy the code
Think for a minute.
We can store resolve and reject as properties of a Promise. When a promise is finished, the resolve/ Reject attribute is called, separating the promise definition from the invocation.
Scheduler.add (() => timeout(time)) is followed by then, indicating that add must be a Promise. The add method can be called immediately, but not necessarily executed immediately, indicating that a queue is maintained to store our tasks.
In addition, a maximum of two tasks can be running at the same time, indicating that a variable must be maintained to store the number of running tasks.
Here’s a solution:
class Scheduler {
constructor() {
this.promises = [];
this.doingJobs = 0;
}
add(promiseCreater) {
return new Promise((resolve, reject) = > {
// The key is to add a callback to the function that is being passed. When resolved, it will return the result.
promiseCreater.resolve = resolve;
promiseCreater.reject = reject;
this.promises.push(promiseCreater);
this.run();
});
}
run() {
if (this.doingJobs < 2 && this.promises.length) {
this.doingJobs += 1;
const promise = this.promises.shift();
promise().then((res) = > {
promise.resolve(res);
})
.catch((err) = > {
promise.reject(err);
})
.finally(() = > {
this.doingJobs -= 1;
this.run(); }); }}}Copy the code
If you have any other answers or questions, please feel free to share them.