上篇使用分段上传文件过程中发现,如果分段过多,将会同时发起多个请求造成阻塞影响用户体验
因此需要将所有分段上传并发请求优化
class TaskQueue {
constructor(tasks, queueSize = 5) {
this.tasks = tasks;
this.queue = [];
this.queueSize = queueSize;
this.executing = []; // 正在执行的任务
}
async initQueue() {
const size = this.tasks.length;
for (const i of Array(size).keys()) {
if (this.tasks.length) {
const fn = this.tasks.shift();
const quePro = Promise.resolve().then(() => fn());
this.queue.push(quePro);
const excutePro = quePro.then((res) => {
// 执行完成后更新执行队列
this.executing.splice(this.executing.indexOf(excutePro), 1);
});
this.executing.push(excutePro);
if (this.queue.length >= this.queueSize) {
await Promise.race(this.executing);
}
}
}
return Promise.all(this.queue);
}
}
export { TaskQueue };
使用
// 上传分段
const taskqueue = new TaskQueue(uploadReqList, 2);
taskqueue
.initQueue()
.then(async (list) => {
if (list.some((item) => item.length === uploadUrlList.length)) {
// 合并文件
const res = await System.completeMultipartUpload({
uploadId: packageInfo.uploadId,
chunkSize: packageInfo.chunkSize,
key: packageInfo.key,
});
form.value.url = res.data || "";
upload.percentage = 100;
}
})
.finally(() => {
upload.percentage = 0;
upload.loading = false;
});