How to make the data from Firestore in to a global variable?

醉酒当歌 提交于 2021-01-27 14:33:43

问题


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

  }

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).


回答1:


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);
});

result will contain the wordLists

Check the following for more information:

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




回答2:


Your variable wordLists is defined (by using let) inside the callback (function) passed to onSnapshot. Even ignoring the fact that that's an asynchronous operation (which Peter's answer tackles using a Promise) – you cannot access a variable defined inside a function outside of that function.

You can learn about variable scoping here on SO, quick n dirty – or in Kyle's excellent you don't know JavaScript series, which is available freely on github or in print. Part 2, Scope & Closures. Also, to actually understand Peter's answer, Async & Performance.



来源:https://stackoverflow.com/questions/59068260/how-to-make-the-data-from-firestore-in-to-a-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!