新建 TaskManager.js
export default class TaskManager {
constructor(maxConcurrentTasks = 1) {
// 最大并发任务数
// to do
// 并发任务数大于1 接口开始有概率返回空值,推测是后端问题
this.maxConcurrentTasks = maxConcurrentTasks;
this.currentTasks = 0;
this.taskQueue = [];
this.allTasksDone = false; // 终结标识
this.allTasksDonePromise = new Promise((resolve) => {
this.resolveAllTasksDone = resolve;
});
}
// 添加任务
addTask(taskFn) {
return new Promise((resolve, reject) => {
this.taskQueue.push({ taskFn, resolve, reject });
this.processQueue();
});
}
// 处理任务队列
async processQueue() {
if (this.currentTasks >= this.maxConcurrentTasks || this.taskQueue.length === 0) {
return;
}
if (this.allTasksDone) {
// 如果已经标记为所有任务完成,则不再处理新任务
return;
}
const { taskFn, resolve, reject } = this.taskQueue.shift();
this.currentTasks++;
try {
const result = await taskFn();
resolve(result);
} catch (error) {
reject(error);
} finally {
this.currentTasks--;
if (this.currentTasks + this.taskQueue.length === 0) {
this.allTasksDone = true;
this.resolveAllTasksDone(); // 标记所有任务完成
}
this.processQueue();
}
}
// 等待所有任务完成
waitForAllTasksDone() {
return this.allTasksDonePromise;
}
}
在项目中使用
import TaskManager from './TaskManager'
taskManager: null,
this.pdfLoading = true
this.taskManager = new TaskManager()
for (let i = 0; i < this.selectionChangeData.length; i++) {
this.taskManager.addTask(() => this.handleDownloadReport(this.selectionChangeData[i]))
}
// 等待所有任务完成
await this.taskManager.waitForAllTasksDone()
this.pdfLoading = false
handleDownloadReport(rowData) {
return new Promise((resolve, reject) => {
const msg = this.$Message.loading({
content: '加载中,请稍等...',
duration: 0
})
let downloadPromises = []
downloadPromises.push(
this.$http.report
.downloadReportExamine({
reportId: rowData.id,
attachmentExtension: 'pdf'
})
.then(respT => {
// xxx
})
)
downloadPromises.push(
this.$http.report
.downloadReport({
reportId: rowData.id,
attachmentExtension: 'pdf'
})
.then(respT => {
// xxx
})
)
Promise.all(downloadPromises)
.then(() => {
msg() // 关闭加载提示
resolve()
})
.catch(error => {
console.error('下载报告时发生错误:', error)
this.$Message.error('下载报告失败')
msg() // 关闭加载提示
reject()
})
})
},