繁体   English   中英

如何从 firebase 存储中存储的文件中获取 URL?

[英]How to get URL from files stored in firebase Storage?

我尝试获取存储在 Firebase 存储中的图片的 URL。 阅读 Firebase 的文档后,我了解到我需要使用 function getDownloadURL() 返回 promise。 以下代码是我目前得到的最接近的解决方案。

getUserPicture(data: UserItem[]) {
data.forEach( async  (item) => {
  const storage = firebase.storage();
  const pathReference = storage.ref(item.userId + '/profile.jpg'); 

  item.picture = await pathReference.getDownloadURL()
  .then((url) => {
      return url.toString();
   })
   .catch((error) => {
       console.error(error);
   });
   console.log('TEST : item.picture: ' + item.picture + ' for user: ' + item.lastname );  
});

}

console.log 返回每个用户的个人资料图片的 URL。 不幸的是,调用 function getUserPicture() 并没有完成工作(item.picture 仍然未定义)。 我认为这是因为顶部 function 应该是异步的,以便在循环中等待进程。

你知道如何解决这样的问题吗?

您不应该在 forEach() 循环中使用 async/await,请参阅“JavaScript: async/await with forEach()”“Using async/await with a forEach loop”

并且由于您并行执行对异步getDownloadURL()方法的可变数量的调用,因此您应该使用Promise.all() ,如下所示:

async getUserPicture(data: UserItem[]) {

    const storage = firebase.storage();
    const promises = [];

    data.forEach((item) => {
        const pathReference = storage.ref(item.userId + '/profile.jpg');
        promises.push(pathReference.getDownloadURL());
    });

    const urlsArray = await Promise.all(promises)

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM