好吧,因为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,
});
});