我有一個包含發布檔案的 firestore 集合,每個檔案都包含對作者(用戶)和案例檔案的參考。
如何在同一個 onSnapshot 中獲取用戶和案例?
這是我想用 await 做的事情,但這似乎不是 react-native-firebase 的選項。
export const firebasePostLooper = (snapshot) => {
let data = [];
snapshot.forEach(async (doc) => {
let newItem = {id: doc.id, ...doc.data()};
if (newItem.author) {
let authorData = await getDoc(newItem.author); // doesn't work with rnfirebase
if (authorData.exists()) {
newItem.userData = {userID: authorData.id, ...authorData.data()};
}
}
if (newItem.case) {
let caseData = await getDoc(newItem.case);
if (caseData.exists()) {
newItem.userData = {userID: caseData.id, ...caseData.data()};
}
}
data.push(newItem);
});
return data;
};
這不起作用,因為getDoc()不存在。
所以我只剩下使用了 .then()
export const firebasePostLooper = (snapshot) => {
let data = [];
snapshot.forEach((doc) => {
let newItem = {id: doc.id, ...doc.data()};
if (newItem.author) {
newItem.author
.get()
.then((res) => {
newItem.authorData = res.data();
if (newItem.case) {
newItem.case
.get()
.then((caseRes) => {
newItem.caseData = caseRes.data();
data.push(newItem);
})
.catch((err) => console.error(err));
}
})
.catch((err) => console.error(err));
} else {
data.push(newItem);
}
});
return data;
};
第二種方法似乎不起作用,return 陳述句中的資料為空,但data.push(newItem)包含正確的檔案以及 2 個參考的檔案。
uj5u.com熱心網友回復:
在資料被填充到承諾中之前,您正在回傳資料。您應該在 .then() 中處理資料的回傳,以便在承諾解決之后而不是之前回傳它。
看看這個例子,如果我們在 Promise 鏈之外處理 emptyData 物件,我們只是在它被填充之前回傳初始值。
let promise = new Promise((resolve, reject)=>{
setTimeout(resolve, 1000, 'foo');
})
let emptyData= [];
let notEmptyData = [];
promise
.then(res=>{
emptyData.push(res);
notEmptyData.push(res);
console.log("Full data: " notEmptyData) // "Full data: foo"
});
console.log("Empty data: " emptyData); // "Empty data: "
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/415657.html
標籤:
