class TaskQueue {
constructor(max) {
this.max = max;
this.taskList = [];
this.aborted = false;
}
restore() {
this.aborted = false;
}
clear() {
this.taskList = [];
this.aborted = true;
}
async start(callSucc = () => { }, callErr = () => { }, allow = () => true) {
if (this.aborted) {
callErr('aborted')
return;
}
let len = this.taskList.length;
if (!len) {
return;
}
let min = Math.min(this.max, len);
for (let i = 0; i < min; i++) {
// 开始占用一个任务的空间
this.max--;
const task = this.taskList.shift();
task&&task().then(res => {
if (allow(res)) {
callSucc(res);
}
}).catch(error => {
callErr(error)
}).finally(() => {
this.max++;
this.start(callSucc, callErr);
})
}
}
addTask(task) {
this.taskList.push(task);
return this;
}
}
console