Firestore +嵌套Promise和ForEach + React-Native

时间:2017-12-10 09:26:10

标签: javascript firebase react-native redux google-cloud-firestore

好吧,因为firestore,我因为使用​​ForEach and nested Promise returns进行嵌套查询而陷入困境。从stackoverflow上的所有帖子开始,我对Promises有了很多了解,然后将它们嵌入ForEach中。但是,我无法找到一个解决方案,我在forEach中嵌入了promise,然后在其中有另一个forEach。

我明白我必须使用Promise.all让root forEach等待,但是如何让它等到.then()也返回一些东西?

firebase.firestore().collection("Feeds").get().then(feedsSnapshot => {
            let promiseArray = [], anotherPromiseArray = [];
            feedsSnapshot.forEach(function (feed) {
                let promise = checkifILikedTheFeed(feed).then(like => {
                    return like;
                }).then(like => {
                    let anotherPromise = firebase.firestore().collection("Feeds").doc(feed.id).collection("Likes").get()
                        .then(likesSnapshot => {
                            if(likesSnapshot.empty){
                                return {
                                    // return myData
                                };
                            } else {
                                let countLikes = 0;
                                likesSnapshot.forEach(likeDoc => {
                                    if(likeDoc.data().isLike){
                                        countLikes++;
                                    }
                                });
                                return {
                                    //myData + countLikes
                                };
                            }
                        });
                    anotherPromiseArray.push(anotherPromise);
                //  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                 // I thought this would work, sadly doesnt.
                });
                promiseArray.push(promise);
            });
            return Promise.all([promiseArray,anotherPromiseArray]);
        }).then(feeds => {
            console.log(feeds);
        //  ^^^^^^^^^^^^^^^^^^^
        //  returns [[undefined],[undefined]]
            dispatch({
                type: 'RETRIEVE_FEEDS',
                payload: feeds,
            });
        });

0 个答案:

没有答案