簡體   English   中英

在將它們推送到數組之前等待 Promises 實現(Javascript Promises)

[英]Wait for Promises to fulfill before push them into an array (Javascript Promises)

問候 Javascript 開發人員

我對 Javascript 和 ReactJS 比較陌生,而且我每天都在學習新事物。 目前我無法擺脫一個問題:

我的組件

useEffect(() => {
    firebase
        .firestore()
        .collection('artworks')
        .doc(props.artworkid)
        .collection('images')
        .get()
        .then(images => {

            let arr = []

            images.docs.forEach(image => {

                arr.push({
                    thumbnail: getImageURL(`${ image.data().imagename }_200x200.${ image.data().imageextension }`),
                    fullres: getImageURL(`${ image.data().imagename }_2000x2000.${ image.data().imageextension }`)
                })

            })

        })
}, [ props.artworkid ])

我的幫手功能

export const getImageURL = (filename) => {
    return firebase
        .storage()
        .ref(filename)
        .getDownloadURL()
        .then(response => {

            return response

        })
}

問題是,我總是得到一個充滿 Promises 的數組,稍后會得到滿足:

[{
    "thumbnail": Promise,
    "fullres": Promise
}, {
    "thumbnail": Promise,
    "fullres": Promise
}, {
    "thumbnail": Promise,
    "fullres": Promise
}, {
    "thumbnail": Promise,
    "fullres": Promise
}]

我的目的是填充對象數組(存儲在 Google Firebase Cloud Storage 上的縮略圖和全分辨率圖像 URL)並將其呈現為此功能組件中的圖庫。

在將 Promise 推送到數組或狀態之前,我如何等待它們首先實現? 我想這與 async/await 有關系……但我無法理解它。 有沒有人可以幫助我?

反應 / Javascript 代碼

你可能想看看Promise.all

useEffect(() => {
    firebase
        .firestore()
        .collection('artworks')
        .doc(props.artworkid)
        .collection('images')
        .get()
        .then(images => {

            let arr = []

            images.docs.forEach(image => {
                const thumbnailPromise = getImageURL(`${ image.data().imagename }_200x200.${ image.data().imageextension }`)

                const fullresPromise = getImageURL(`${ image.data().imagename }_2000x2000.${ image.data().imageextension }`)

                Promise.all([thumbnailPromise, fullresPromise])
                    .then(values => {
                        arr.push({
                            thumbnail: values[0],
                            fullres: values[1]
                        })
                    });
            })

        })
}, [ props.artworkid ])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM