简体   繁体   中英

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

Greetings Javascript developers

I'm relatively new to Javascript and ReactJS and I'm still learning new things every day. Currently I can't get rid of a problem:

My Component

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 ])

My helper function

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

            return response

        })
}

The problem is, that I always get an array full of Promises, which get fulfilled later:

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

My intention is to populate the array of objects (thumbnail and fullres image URLs stored on Google Firebase Cloud Storage) and render it as image gallery in this functional component.

How can I wait for the Promises to fulfill first before I push them into an array or State? I guess it has something to do with async/await… but I can't wrap my head arout it. Is there anyone able to help me?

反应 / Javascript 代码

You probably want to look at 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 ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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