等待承诺完成,然后将其放入数组(Javascript承诺)

时间:2020-10-14 21:51:23

标签: javascript reactjs firebase asynchronous google-cloud-storage

问候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中存储的缩略图和Fullres图像URL),并在此功能组件中将其呈现为图库。

在将它们放入数组或状态之前,我如何等待它们首先完成?我想这与async / await有关...但是我无法将其包裹在头上。有没有人可以帮助我?

React / Javascript code

1 个答案:

答案 0 :(得分:2)

您可能想看看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 ])