[英]How to save firebase returned data to a variable
我正在为我的 React Native 应用程序编码,但无法从firebase.firestore().collection("test_data").doc(ID)
循环之外的firebase.firestore().collection("test_data").doc(ID)
返回获取数据。 每当我在循环后检查dataArray
变量时,它都是空的。 如果我在循环中检查它,数据就在那里。 我认为这是一个范围问题,但我只是不明白。 我也无法在循环内调用任何用户定义的函数。
try {
let dataArray = [];
// get the document using the user's uid
firebase.firestore().collection("users").doc(uid).get()
.then((userDoc) =>{
// if the document exists loop through the results
if (userDoc.exists) {
data = userDoc.data().saved_data; // an array store in firebase
data.forEach(ID => { // loop through array
firebase.firestore().collection("test_data").doc(ID).get()
.then((doc) => {
dataArray.push(doc.data().test_data);
console.log(dataArray) // the data shows
})
console.log(dataArray) // the data does not show
})
}
})
}
catch (error) {
}
}
您正在循环异步调用,因此您的最终 console.log 将在收到数据之前触发。 您的第一个 console.log 仅在收到数据后触发。
所以代码正在运行,但函数(承诺)将在从您的 firebase 调用接收到所有数据之前解析(未定义或无效)。
如果要将数组返回给调用者,可以执行以下操作:
function getDataFromServer() {
// get the document using the user's uid
return firebase.firestore().collection('users').doc(uid).get().then(userDoc => {
// now we're returning this promise
const dataArray = []; // can move this to lower scope
// if the document exists loop through the results
if (userDoc.exists) {
const savedData = userDoc.data().saved_data; // an array store in firebase
return Promise.all(
// wait for all the data to come in using Promise.all and map
savedData.map(ID => {
// this will create an array
return firebase.firestore().collection('test_data').doc(ID).get().then(doc => {
// each index in the array is a promise
dataArray.push(doc.data().test_data);
console.log(dataArray); // the data shows
});
})
).then(() => {
console.log(dataArray);
return dataArray; // now data array gets returned to the caller
});
}
return dataArray; // will always be the original empty array
});
}
现在该函数返回一个数组的承诺,所以你可以做...
const dataArray = await getDataFromServer()
或者
getDataArrayFromServer().then(dataArray => {...})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.