我们有个需求是这样的,批量下载多个文件,要求这几个文件是同时下载并且出现在浏览器的下载栏的
正常写代码是这样的,也是错误案例
// 文件下载接口
export async function downloadFile(params?: any) {
return request(`url`, {
params,
responseType: 'blob',
getResponse: true,
});
}
// 调用的位置
downloadFile({ fileUuid}).then((res) => {
const fileName =
res.response?.headers ?.get('content-disposition') ?.split('attachment;filename=')[1] || '';
downImgFile(decodeURI(fileName), res.data);
});
但是你会发现,你选择10个文件,F12打开控制台,接口是请求了10次,但是浏览器的下载栏只成功了最后一个,这是因为异步原因导致的,这时候我们就需要用到 promise.all
成功截图:
现在就来演示正确代码
const requests = files.map((item: string) => {
return downloadFile({ fileUuid :item}).then((res) => {
const fileName =res.response?.headers ?.get('content-disposition') ?.split('attachment;filename=')[1] || '';
downImgFile(decodeURI(fileName), res.data);
});
});
Promise.all(requests).then(() => {
// 这里写下载成功后,需要做的处理
});