function timeout (time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, time);
});
}
class SuperTask {
constructor (maxTaskCount = 2) {
// 最大任务执行数量
this.maxTaskCount = maxTaskCount;
// 正在执行任务数量
this.runTaskCount = 0;
// 需要执行的任务
this.tasks = [];
}
add (task) {
return new Promise((resolve, reject) => {
this.tasks.push({
task,
resolve,
reject,
});
this._run();
});
}
// 执行任务
_run () {
while (this.runTaskCount < this.maxTaskCount && this.tasks.length) {
this.runTaskCount++;
const { task, resolve, reject } = this.tasks.shift();
task().then(resolve, reject).finally(() => {
this.runTaskCount--;
this._run();
});
}
}
}
const superTask = new SuperTask();
function addTask (time, name) {
superTask.add(() => timeout(time)).then(() => {
console.log(`任务${name}完成`);
});
}
addTask(1000 * 10, 1); //10秒后输出:任务1完成
addTask(1000 * 5, 2); //5秒后输出:任务2完成
addTask(1000 * 3, 3); //8秒后输出:任务3完成
addTask(1000 * 4, 4); //12秒后输出:任务4完成
addTask(1000 * 5, 5); //15秒后输出:任务5完成