refactor(DownloadAll): 并行下载

This commit is contained in:
awalol
2025-07-14 00:56:30 +08:00
committed by awalol
parent 17200150dd
commit 2da766168c

View File

@@ -7,7 +7,8 @@ export function DownloadAll() {
const files = useAppSelector(selectFiles); const files = useAppSelector(selectFiles);
const onClickDownloadAll = async () => { const onClickDownloadAll = async () => {
console.time('DownloadAll'); //开始计时 console.time('DownloadAll'); //开始计时
if (Object.keys(files).length === 0) { const fileCount = Object.keys(files).length;
if (fileCount === 0) {
toast.warning('未添加文件'); toast.warning('未添加文件');
return; return;
} }
@@ -21,7 +22,6 @@ export function DownloadAll() {
//过滤处理失败的文件 //过滤处理失败的文件
const completeFiles = Object.values(files).filter((file) => file.state === ProcessState.COMPLETE); const completeFiles = Object.values(files).filter((file) => file.state === ProcessState.COMPLETE);
const fileCount = Object.keys(files).length;
//开始下载 //开始下载
let dir: FileSystemDirectoryHandle | undefined; let dir: FileSystemDirectoryHandle | undefined;
@@ -35,33 +35,29 @@ export function DownloadAll() {
} }
toast.warning('开始下载,请稍候'); toast.warning('开始下载,请稍候');
let success = 0; const promises = Object.values(completeFiles).map(async (file) => {
const promises: Promise<void>[] = []; console.log(`开始下载: ${file.fileName}`);
for (const [_, file] of Object.entries(completeFiles)) { try {
const promise = new Promise<void>((resolve, reject) => { if (dir) {
console.log(`开始下载: ${file.fileName}`); await DownloadNew(dir, file);
const action = dir ? DownloadNew(dir, file) : DownloadOld(file); } else {
action.then( await DownloadOld(file);
() => { }
console.log(`成功下载: ${file.fileName}`); console.log(`成功下载: ${file.fileName}`);
success++; } catch (e) {
resolve(); console.error(`下载失败: ${file.fileName}`, e);
}, toast.error(`出现错误: ${e}`);
(e) => { throw e;
console.error(`下载失败: ${file.fileName}`, e); }
toast.error(`出现错误: ${e}`); });
reject(e); await Promise.allSettled(promises).then((f) => {
}, const success = f.filter((result) => result.status === 'fulfilled').length;
); if (success === fileCount) {
}); toast.success(`成功下载: ${success}/${fileCount}`);
promises.push(promise); } else {
} toast.warning(`成功下载: ${success}/${fileCount}`);
try { }
await Promise.allSettled(promises); });
toast.success(`成功下载: ${success}/${fileCount}`);
} catch {
toast.warning(`成功下载: ${success}/${fileCount}`);
}
console.timeEnd('DownloadAll'); //停止计时 console.timeEnd('DownloadAll'); //停止计时
}; };