[英]How do I access the value returned by promise firestore?
我正在嘗試訪問 secondSnapshot.data() 返回的內容,但遇到了問題,如下面的評論所述。 我試圖創建一個異步 function,但無濟於事。 知道出了什么問題嗎? 請查看 2 條評論。
useEffect(() => {
firestore.collection(`comments`).onSnapshot((snapshot) => {
const posts = snapshot.docs
.map((doc) => {
const address = doc.data().comments?.map((comment) => {
comment.get().then((secondSnapshot) => {
console.log("snapshot", secondSnapshot.data());
#I SEE WHAT I EXPECT TO SEE
return secondSnapshot.data();
});
});
console.log(address) #THIS RETURNS UNDEFINED FOR SOME REASON??
return {
username: doc.data().username,
date: doc.data().date.seconds,
text: doc.data().text,
votes: doc.data().votes,
comments: [],
};
});
props.setComments(posts);
});
}, [location]);
除了@Mulan 指出的 React vs Firebase 設計問題之外,您的代碼還有幾個問題。
以下 map function 不返回任何內容。 如果您不從該塊返回某些內容,您將不會在地址中找到任何內容。
const address = doc.data().comments?.map((comment) => {
/* This MUST return something */
});
您正在混合同步和異步代碼。 基本上,您嘗試在對comment.get()
的不同異步調用完成運行之前打印地址值。
const address = doc.data().comments?.map((comment) => {
/* async code inside */
});
console.log(address); // this runs without waiting for the async code
如果您在使用舊的 promise 語法時遇到困難,請嘗試使用 async / await 代替:
firestore.collection(`comments`).onSnapshot(async (snapshot) => {
const postPromises = snapshot.docs
.map(async (doc) => {
const comments = doc.data().comments ?? []; // assign an empty array if there are no comments
const secondSnapshots = await Promise.all(comments.map((comment) => comment.get()));
const addresses = secondSnapshots.map((secondSnapshot) => secondSnapshot.data());
console.log(addresses);
return { /* ... */ };
});
const posts = await Promise.all(postPromises);
props.setComments(posts);
});
我不確定您是否應該在onSnapshot
中調用comment.get()
,但這是另一回事,我不是 Firebase 專家。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.