编写并发请求控制类
class SuperTask {
constructor(parallelCount = 2) {
this.parallelCount = parallelCount;
this.tasks = [];
this.runningCount = 0;
}
_run() {
while (this.runningCount < this.parallelCount && this.tasks.length) {
const { task, resolve, reject } = this.tasks.shift();
this.runningCount++;
Promise.resolve(task())
.then(resolve, reject)
.finally(() => {
this.runningCount--;
this._run();
});
}
}
add(task) {
return new Promise((resolve, reject) => {
this.tasks.push({ task, resolve, reject });
this._run();
});
}
}
测试使用
const superTask = new SuperTask(2);
function request(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve(time);
}, time);
});
}
function addTask(time) {
superTask
.add(() => request(time * 100))
.then(data => {
console.log(`任务${time}执行完毕`);
console.log(data);
});
}
for (let i = 1; i < 100; i++) {
addTask(i);
}