首页 > 解决方案 > 解压缩文件并以角度将内容上传到Firestore后如何调用函数?

问题描述

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

虽然我的函数在填充我的 termObj 之前立即被调用。我试图保存承诺并等到它们全部解决,但 promise.all 正在立即执行(它不等待承诺在 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);
});

} // 方法结束

=============Edit========== 在 for 循环结束后立即移动 await Promise.all 语句,然后 console.log termObj.all_images 给我同样的结果。

console.log(termObj.all_images) 的输出

标签: javascriptangularpromiseasync-awaitunzip

解决方案


移动这个

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

就在关闭 for of 之后。

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


推荐阅读