uniapp队列下载
uniapp 实现队列下载的方法
在 uniapp 中实现队列下载通常需要管理多个下载任务,确保它们按顺序执行。可以通过以下方法实现:
使用 Promise 和递归实现队列下载
定义一个下载队列数组,通过递归或循环逐个处理下载任务。
const downloadQueue = [];
let isDownloading = false;
function addToQueue(url) {
downloadQueue.push(url);
if (!isDownloading) {
processQueue();
}
}
function processQueue() {
if (downloadQueue.length === 0) {
isDownloading = false;
return;
}
isDownloading = true;
const url = downloadQueue.shift();
uni.downloadFile({
url: url,
success: (res) => {
if (res.statusCode === 200) {
console.log('下载成功', res.tempFilePath);
}
},
complete: () => {
processQueue();
}
});
}
使用 async/await 实现顺序下载
利用 async/await 可以更清晰地管理异步下载任务。
async function downloadFilesSequentially(urls) {
for (const url of urls) {
try {
const res = await new Promise((resolve, reject) => {
uni.downloadFile({
url: url,
success: resolve,
fail: reject
});
});
console.log('下载完成', res.tempFilePath);
} catch (error) {
console.error('下载失败', error);
}
}
}
并发控制下载
如果需要控制并发数,可以使用类似以下方法:
async function downloadWithConcurrency(urls, maxConcurrent = 3) {
const queue = [];
let activeDownloads = 0;
urls.forEach(url => {
queue.push(() =>
new Promise((resolve) => {
activeDownloads++;
uni.downloadFile({
url,
success: (res) => {
console.log('下载完成', res.tempFilePath);
resolve();
},
complete: () => {
activeDownloads--;
next();
}
});
})
);
});
function next() {
if (activeDownloads < maxConcurrent && queue.length) {
const task = queue.shift();
task();
}
}
for (let i = 0; i < Math.min(maxConcurrent, urls.length); i++) {
next();
}
}
注意事项
- 下载大文件时需要考虑内存问题
- 网络异常时需要添加重试机制
- 可能需要处理文件保存路径问题
- 在微信小程序中需要注意域名白名单配置
扩展功能
可以添加以下功能增强下载队列:
- 进度监控
- 暂停/继续功能
- 断点续传
- 错误重试机制
以上方法可以根据实际需求进行调整和组合使用。







