我撰寫了代碼來檢索存盤在我的 Firebase 存盤桶中的影像的 url 并將它們加載到一個imageUrls陣列中。
該代碼在大約 80% 的實體中作業,但對于其余的(看似隨機的 20%),當代碼運行時,它無法解決一些承諾,但也不會引發例外。
代碼:
async function loadImages() {
// Load image urls from firebase storage
Object.values(imageOrder).forEach(async (fileName, index) => { // Iterate through each imageName for image that should be loaded (e.g., "dogs.jpg", "mountains.jpeg")
const imgRef = ref(storage, `images/projects/${project.id}/draft/${fileName}`)
const imgUrl = await getDownloadURL(imgRef) // this promise may never get resolved for some iterations of the loop
const imgPos = index // store index in array at which this image should be inserted into
setImageUrls(prevState => {
let newArray = [...prevState]
newArray = newArray.map((item, index) => index === imgPos ? imgUrl : item) // replace null value in array with loaded image url at appropriate index
return newArray
})
})
}
永遠不會得到解決的承諾出現在上面的行中const imgUrl = await getDownloadURL(imgRef)。
我在不同的地方插入了控制臺日志陳述句,以了解正在發生的事情的細節。我期望的所有影像名稱都在forEach回圈中迭代,并imgRef為每個影像創建一個參考。
但在某些情況下,只有一部分 Promise 得到解決。在其余部分,await陳述句之后的代碼不會被呼叫,因此結果imageUrls陣列包含 url 字串和null值的組合。
為什么會發生這種情況?我還能做些什么來進一步澄清問題嗎?謝謝。
uj5u.com熱心網友回復:
您可以嘗試getDownloadURL()使用Promise.all(). 嘗試重構代碼,如下所示:
async function loadImages() {
// Load image urls from firebase storage
const promises = [];
Object.values(imageOrder).forEach(image => {
const imgRef = ref(storage, `images/projects/${project.id}/draft/${fileName}`);
promises.push(getDownloadURL(imgRef));
})
const urls = (await Promise.all(promises)).filter(url => !!url);
setImageUrls(urls);
}
from 的回傳值
Promise.all()將按照 Promises 傳遞的順序排列,無論完成順序如何。
因此,您不需要使用index. at end也filter()洗掉了任何null值。
還結帳:使用 async/await 和 forEach 回圈
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/469213.html
