简体   繁体   中英

React native returns Promise instead of value Firestore

So I'm trying to fetch multiple documents from Firestore basen on an array of IDs (yummed) which are saved in my users collection. I first fetch the IDs and then I have a map function which finds each document from the recipes collection and assigns it to variable data. The problem is that instead of getting just the result for each ID, I get a Promise for each of the IDs. How can I fix this in order to get just the data?

export const yummedRecipesFetch = () => {
    const { currentUser } = firebase.auth();
    return (dispatch) => {
        firebase.firestore().collection(`users`).doc(currentUser.uid)
            .onSnapshot(function(doc) {
                var data = doc.data().yummed.map(function (recipeId) {
                    return firebase.firestore().collection(`recipes`).doc(recipeId).get().then(function(doc) {
                        return { id: doc.id, ...doc.data()};
                    })                    
                })
                console.log(data)
                dispatch({ type: YUMMED_RECIPES_FETCH_SUCCESS, payload: data })
            });
    };
};

Using the suggestion above Promise.all

export const yummedRecipesFetch = () => {
    const { currentUser } = firebase.auth();
    return (dispatch) => {
        firebase.firestore().collection(`users`).doc(currentUser.uid)
            .onSnapshot(function(doc) {
                var data = doc.data().yummed.map(function (recipeId) {
                    return firebase.firestore().collection(`recipes`).doc(recipeId).get().then(function(doc) {
                        return { id: doc.id, ...doc.data()};
                    })                    
                })
                Promise.all( data).then(function(values) {
                    dispatch({ type: YUMMED_RECIPES_FETCH_SUCCESS, payload: values })
                })
            });
    };
};

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