94 lines
2.4 KiB
JavaScript
94 lines
2.4 KiB
JavaScript
export class ConcurrentRequestController {
|
|
constructor(maxConcurrency = 5) {
|
|
this.maxConcurrency = maxConcurrency;
|
|
this.activeCount = 0;
|
|
this.queue = [];
|
|
this.abortControllers = new Map();
|
|
this.isCancelled = false;
|
|
}
|
|
|
|
// 添加请求到控制器
|
|
addRequest(requestFn) {
|
|
if (this.isCancelled) {
|
|
return Promise.reject(new Error('请求控制器已被取消'));
|
|
}
|
|
|
|
const abortController = new AbortController();
|
|
const signal = abortController.signal;
|
|
|
|
return new Promise((resolve, reject) => {
|
|
const task = () => {
|
|
if (this.isCancelled) {
|
|
reject(new Error('请求控制器已被取消'));
|
|
return;
|
|
}
|
|
const taskId = Date.now() + '_' + Math.random().toString(36);
|
|
this.abortControllers.set(taskId, abortController);
|
|
this.activeCount++;
|
|
requestFn(signal)
|
|
.then(result => {
|
|
if (!this.isCancelled) {
|
|
resolve(result);
|
|
}
|
|
})
|
|
.catch(error => {
|
|
if (!this.isCancelled || error.name !== 'AbortError') {
|
|
reject(error);
|
|
}
|
|
})
|
|
.finally(() => {
|
|
this.activeCount--;
|
|
this.abortControllers.delete(taskId);
|
|
this._processQueue();
|
|
});
|
|
};
|
|
|
|
// 如果当前活跃请求数小于最大并发数,立即执行
|
|
if (this.activeCount < this.maxConcurrency) {
|
|
task();
|
|
} else {
|
|
// 否则加入队列等待
|
|
this.queue.push(task);
|
|
}
|
|
});
|
|
}
|
|
|
|
// 处理等待队列中的任务
|
|
_processQueue() {
|
|
if (this.queue.length > 0 && this.activeCount < this.maxConcurrency && !this.isCancelled) {
|
|
const nextTask = this.queue.shift();
|
|
nextTask();
|
|
}
|
|
}
|
|
|
|
// 取消所有请求(已开始和未开始的)
|
|
cancelAll() {
|
|
if (this.isCancelled) {
|
|
return
|
|
};
|
|
|
|
this.isCancelled = true;
|
|
|
|
// 取消所有正在进行的请求
|
|
this.abortControllers.forEach(controller => {
|
|
controller.abort();
|
|
});
|
|
|
|
// 清空等待队列
|
|
this.queue = [];
|
|
this.activeCount = 0;
|
|
this.isCancelled = false;
|
|
this.abortControllers.clear();
|
|
console.log('所有请求已取消');
|
|
}
|
|
|
|
// 获取当前状态
|
|
getStatus() {
|
|
return {
|
|
activeCount: this.activeCount,
|
|
queueLength: this.queue.length,
|
|
maxConcurrency: this.maxConcurrency,
|
|
isCancelled: this.isCancelled
|
|
};
|
|
}
|
|
} |