如何将数据从Firestore转换为全局变量? [英] How to make the data from Firestore in to a global variable?
本文介绍了如何将数据从Firestore转换为全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使值返回到onSnapshot函数之外?
How can I make the value return outside the onSnapshot function?
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)
在函数之外,这就是为什么我无法获得其值的原因.您能否给我一个关于如何在函数外部调用它的想法(如果可能的话).
I knew that the console.log("words1: ", wordLists)
is outside the function that's why I can't get its value. Could you please give me an idea on how can I call it outside the function (if possible).
推荐答案
要在外部访问它,可以使用 Promise
:
To access it outside, you can use 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
});
然后访问外部,请执行以下操作:
Then to access outside do the following:
checkIfExisting().then((result) => {
console.log(result);
});
结果
将包含 wordLists
检查以下内容以获取更多信息:
Check the following for more information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
这篇关于如何将数据从Firestore转换为全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文