使用场景: 1.maxLength为1,可以控制发送顺序 2.性能优化,控制并发数量,减少对服务端的冲击
注意:1.arr装函数 2.每个函数要有个对应的index 3.要有结果arr 4.通过resolve传递
class Task {
taskArr = [];
limit = 1;
result = [];
nextIndex = 0;
constructor(limit = 1) {
this.limit = limit;
}
async nextRun(resolve) {
// const current = this.currentIndex++;
const current = this.nextIndex++;
// console.log("result", "res");
if (!this.result.includes(false)) {
return resolve(this.result);
}
try {
const res = await this.taskArr[current]();
// console.log("result", res);
this.result[current] = res;
} catch (error) {
this.result[current] = error;
// console.log("result", "error", error);
}
this.nextRun(resolve);
}
run() {
this.result =
[false, false, false, false, false] ||
new Array(this.taskArr.length).fill(false);
return new Promise((resolve, reject) => {
while (this.nextIndex <= this.limit) {
//外层的同步会忽略里层的async await 还是将其做同步处理
this.nextRun(resolve);
}
});
}
setTaskArr(arr) {
if (Array.isArray(arr)) {
arr.forEach((r) => {
if (r instanceof Function) {
return;
}
throw Error("请传入函数");
});
}
this.taskArr = arr;
return this.run();
}
}
const f = () => {
return new Promise((res, rej) => {
console.log();
setTimeout(() => {
res("11111");
}, 2000);
});
};
new Task(2).setTaskArr([f, f, f, f, f, f, f]).then((res) => {
console.log(res, ":res");
});