如何将 Firestore 中的数据转换为全局变量?



如何使值在 onSnapshot 函数之外返回?

function checkIfExisting(){
const collection = firebase.firestore().collection("audit");
const getCaseID = collection.where("caseID", "==", "00001234");
getCaseID.onSnapshot(function(querySnapshot) {
let wordLists = [];
querySnapshot.forEach(function(doc) {
//get all the scanned words under "word" field in the Firestore Database
wordLists.push(doc.data().word);
});
console.log("words: ", wordLists);// return a value
});
console.log("words1: ", wordLists);// undefined
}

我知道console.log("words1: ", wordLists)在函数之外,这就是为什么我无法获得它的价值。您能否告诉我如何在函数外部调用它(如果可能的话(。

要在外面访问它,您可以使用Promise

function checkIfExisting(){
return new Promise((resolve, reject) => {
const collection = firebase.firestore().collection("audit");
const getCaseID = collection.where("caseID", "==", "00001234");
getCaseID.get().then(function(querySnapshot) {
let wordLists = [];
querySnapshot.forEach(function(doc) {
//get all the scanned words under "word" field in the Firestore Database
wordLists.push(doc.data().word);
resolve(wordLists);
});
console.log("words: ", wordLists);// return a value
});

然后,要访问外部,请执行以下操作:

checkIfExisting().then((result) => {
console.log(result);
});

result将包含wordLists

有关详细信息,请查看以下内容:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

>你的变量wordLists是在传递给onSnapshot的回调(函数(中定义的(通过使用let(。即使忽略这是一个异步操作的事实(Peter 的答案使用 Promise 解决了这个问题(,您也无法访问在该函数之外的函数内定义的变量。

你可以在SO,quickn dirty - 或者在Kyle的优秀你不知道JavaScript系列中了解变量范围,该系列可在github或印刷版上免费获得。第 2 部分,范围和闭包。 另外,要真正理解彼得的答案,Async & Performance

最新更新