【问题标题】:How to make the data from Firestore in to a global variable?如何将 Firestore 中的数据转换为全局变量?
【发布时间】:2020-02-06 15:58:05
【问题描述】:

如何使值在 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) 在函数之外,这就是我无法获得它的值的原因。您能否告诉我如何在函数之外调用它(如果可能)。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    要在外面访问,可以使用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

    【讨论】:

      【解决方案2】:

      您的变量wordLists 是在传递给onSnapshot 的回调(函数)中定义的(通过使用let)。即使忽略这是一个异步操作的事实(彼得的回答使用 Promise 解决) - 您无法访问该函数之外的函数内部定义的变量。

      您可以了解变量作用域here on SO, quick n dirty - 或在 Kyle 的优秀你不懂 JavaScript 系列中,available freely on github 或印刷版。第 2 部分,范围和闭包。 另外,要真正理解 Peter 的回答,Async & Performance。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多