【问题标题】:How to wait until all data is downloaded in Firebase (Firestore) Storage?如何等到所有数据都下载到 Firebase(Firestore)存储中?
【发布时间】:2018-12-03 02:46:43
【问题描述】:

我正在使用 Firestore 和 Storage 在 Vue 中制作一个轻型仪表板。我不是专业人士,所以我陷入了应该很容易的事情。我有一个函数应该根据文件名获取所有 URL(这就是存储的工作方式)

getImages: function(uid, images) {        
    images.forEach((filename) => {
        var ref = firebaseApp.storage().ref('images/' + uid + "/" + filename);
        ref.getDownloadURL().then(function(url) {   
          this.finalImages.push(url)
          console.log(url);
        }).catch(function(error) {
          switch (error.code) {
            case 'storage/object_not_found':
              // File doesn't exist
              console.log('Object not found');
              break;

            case 'storage/unauthorized':
              // User doesn't have permission to access the object
              console.log('You do not have the right permissions');
              break;

            case 'storage/canceled':
              // User canceled the upload
              console.log('Canceled');
              break;

            case 'storage/unknown':
              // Unknown error occurred, inspect the server response
              console.log('Who knows...');
              break;
          }
        })
    })
  }

但是 URL 会在代码完成后下载,所以我从来没有看到它们。如何停止一切并等待 URL 出现在 finalImages 数组中然后继续?

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore firebase-storage


    【解决方案1】:

    您可以将每个请求映射到一个承诺,然后等待所有承诺完成:

    getImages: function(uid, images) {        
      Promise.all(images.map((filename) => {
        return new Promise((resolve, reject) => {
          var ref = firebaseApp.storage().ref('images/' + uid + "/" + filename);
          ref.getDownloadURL().then(function(url) {
            resolve(url);
          }).catch(function(error) {
            // Uncomment this line to ignore errors.
            reject(error);
            switch (error.code) {
              case 'storage/object_not_found':
                // File doesn't exist
                console.log('Object not found');
                break;
    
              case 'storage/unauthorized':
                // User doesn't have permission to access the object
                console.log('You do not have the right permissions');
                break;
    
              case 'storage/canceled':
                // User canceled the upload
                console.log('Canceled');
                break;
    
              case 'storage/unknown':
                // Unknown error occurred, inspect the server response
                console.log('Who knows...');
                break;
            }
          })
        });
      })).then((finalImages) => {
        // all images.
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 2011-10-31
      相关资源
      最近更新 更多