如何在解压文件并将内容上传到angular中的Firestore后调用函数



我从用户那里得到了一个图像和csv文件的压缩文件。我需要解压缩这些文件并上传到Firestore。当我上传图像时,我还想将下载图像的路径保存在稍后推送的图像对象中。我想保存我推送的所有图像对象的id,并将它们保存在术语对象中。我想等到我的所有文件都上传后再调用一些其他函数。

不过,我的函数在填充termObj之前立即被调用。我试图保存promise并等待它们全部解决,但promise.all正在立即执行(它不等待promise在for循环中填充)

在调用this.printDone()之前,如何等待所有文件上传并填充termObj?

async fileChanged(event) {
const file = event.target.files[0];
const self = this;
let promises= [];
let termObj = {
all_images: [],
};
this.zipService.getEntries(file).subscribe( (next) => {
for (const ent of next) {
let filename : string = ent.filename;
const fileType = filename.slice(filename.indexOf("."));
this.zipService.getData(ent).data.subscribe(async function(val) {
let blobFile = new File([val], filename);
self.task =  self.storage.upload(self.authService.getUser() +  "/" +filename, blobFile);

if( fileType === '.jpg' || fileType === '.jpeg' || fileType === '.png'){
let pathToFile = self.authService.getUser() + '/' + filename;
// URL
await firebase.storage().ref().child( pathToFile ).getDownloadURL().then(function (url) {
let imageObj = {
downloadURL: url,
};
const imagePromise = self.db.collection('images').add(imageObj).then(function(ref){
termObj.all_images.push(ref.id);
console.log(termObj);
});
promises.push(imagePromise);
});
}
}); // end of unzip service that gets data from zipped entry
} // end of for loop looping through files
}); //gets entries from zipped file
await Promise.all(promises).then(()=>{
this.printDone();
console.log(termObj.all_images);
});

}//方法结束

===============编辑==========将await Promise.all语句移到for循环结束后,再将termObj.all_images移到console.log中,会得到相同的结果。

console.log(termObj.all_images)的输出

移动此

await Promise.all(promises).then(()=>{
this.printDone();
console.log(termObj.all_images);});

刚刚关闭的。

您的问题是因为订阅是异步的(您已经知道了),但这意味着当到达此代码时,promise数组是空的。

最新更新