我嘗試獲取存盤在 Firebase 存盤中的圖片的 URL。閱讀 Firebase 的檔案后,我了解到我需要使用回傳承諾的函式 getDownloadURL()。以下代碼是我目前得到的最接近的解決方案。
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。不幸的是,函式 getUserPicture() 的呼叫并沒有完成作業(item.picture 仍然未定義)。我認為這是因為頂層函式應該是異步的,以便在回圈中等待行程。
你知道如何解決這樣的問題嗎?
uj5u.com熱心網友回復:
您不應該在 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)
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/510138.html
標籤:Google Cloud Collective javascript有角度的火力基地异步等待
