【发布时间】:2021-03-20 13:45:03
【问题描述】:
我尝试了很多搜索这个问题,但没有得到任何帮助我的东西。
我正在尝试使用 URL 从 Strapi 下载一堆 pdf 文件,并在下载每个 pdf 后将其推送到一个文件夹中以创建一个 zip。
我的问题是在下载时,由于文件太大,很少有文件无法推送到 zip 文件夹中。基本上,zip 创建是不等待完成下载。
这是我的代码,我使用 map() 获取 URL 并使用 blob() 下载它,然后使用 zip 将其保存在 zip 文件夹中。
const downloadPdf = async (newData: any) => {
return new Promise(async (resolve) => {
let PolicyDocData: any;
[...some operation...]
if (newData.laws) {
if (newData.laws.description[0]) {
[...some operation to create an array for URL...]
let lawDoc = Array.from(new Set(lawDocArray));
lawDoc.map(async (val: any, index: any) => {
const lawUrl = val.url.slice(1);
const DocUrl = serverUrl + lawUrl;
let download = await fetch(DocUrl, {
method: "GET",
}).then((response) => response.blob()).then((response) => {
let fileType = ".pdf";
const timeStamp = Math.floor(Date.now() / 1000);
const fileName = val.name;
let docFileName = fileName + "_" + timeStamp;
zip.folder("Compliance/Laws").file(docFileName + fileType, response);
})
if (lawDoc.length - 1 === index) {
resolve(Contents);
}
})
}
}
}).then((Contents: any) => {
if (Contents) {
Packer.toBlob(PolicyDocumentCreator(Contents)).then((blob) => {
zip.generateAsync({ type: "blob" }).then(function (content: any) {
saveAs(content, folderName ? folderName : complianceName + ".zip");
setLoading(false);
})
});
}
});
};
我尝试使用 setTimeout() 解决它,但这不是一个可行的解决方案。
【问题讨论】:
-
下载完成后为什么不将文件夹压缩到
then中?像这样:Promise.all().then( ) -
是的,我按照你的建议试过了,但又遇到了同样的问题。 @GiladShnoor
-
new Promise(async function (resolve, reject) { resolve(content) });完全没有意义,你想达到什么目的? -
不要将
async函数作为回调传递给then!如果您想使用async/await,则根本不需要then- 请改用await。 -
if (lawDoc.length - 1 === index) { resolve(Contents); }看起来很像Promiseconstructor antipattern。您可能正在寻找Promise.all?!
标签: react-native promise async-await strapi