bla*_*ght 1 javascript firebase reactjs google-cloud-firestore
我正在为我的 React Native 应用程序编码,但无法从firebase.firestore().collection("test_data").doc(ID)循环外的 firebase 返回中获取数据。每当我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) {
}
}
Run Code Online (Sandbox Code Playgroud)
您正在循环异步调用,因此您的最终 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
});
}
Run Code Online (Sandbox Code Playgroud)
现在该函数返回一个数组的承诺,所以你可以做...
const dataArray = await getDataFromServer()
或者
getDataArrayFromServer().then(dataArray => {...})
| 归档时间: |
|
| 查看次数: |
362 次 |
| 最近记录: |