簡體   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