我们要实现如下的一个 TaskPro 的类,它允许用户添加一系列的任务,并按照添加的顺序依次执行这些任务。用户可以手动调用next执行下一个任务,如果没有调用next,实现的类中需要主动调用下一个任务进行执行。
根据如下代码,需要实现TaskPro类:
const t = new TaskPro();
t.addTask(async (next) => {
console.log(1, "start");
await next();
console.log(1, "end");
});
t.addTask(() => {
console.log(2);
});
t.addTask(() => {
console.log(3);
});
t.run(); // 1,start,2,3,1,end
实现的TaskPro类如下:
class TaskPro {
constructor() {
this._taskList = [];
this._isRunning = false;
this._currentIndex = 0;
this._next = async () => {
this._currentIndex++;
await this._runTask();
};
}
addTask(task) {
this._taskList.push(task);
}
run() {
// 如果正在运行或者没有任务,则直接返回
if (this._isRunning || !this._taskList.length) {
return;
}
this._isRunning = true;
this._runTask();
}
/**
* 取出一个任务执行
*
*/
async _runTask() {
if (this._currentIndex >= this._taskList.length) {
this._reset();
return;
}
const i = this._currentIndex;
const task = this._taskList[this._currentIndex];
await task(this._next);
const j = this._currentIndex;
if (i === j) {
await this._next();
}
}
_reset() {
this._taskList = [];
this._isRunning = false;
this._currentIndex = 0;
}
}