Javascript 如何将从Firestore.collection().get().then()方法获取的数据分配给全局变量

Javascript 如何将从Firestore.collection().get().then()方法获取的数据分配给全局变量,javascript,firebase,web,google-cloud-firestore,Javascript,Firebase,Web,Google Cloud Firestore,我想从Firebase FireStore获取数据(文档中的特定字段)→ 将该值赋给全局变量→ 记录该值 我到目前为止的研究: 我尝试将值赋给全局变量→ 不起作用 我尝试返回获取的值 var a=firestore.collection(“collection1”).doc(“doc1”).get().then(){return doc.data().FIELD} 从上面的列表中删除return关键字 目前,我正在then()中执行类似console.log()的嵌套代码 我的代码现在是什么样子

我想从Firebase FireStore获取数据(文档中的特定字段)→ 将该值赋给全局变量→ 记录该值

我到目前为止的研究:

  • 我尝试将值赋给全局变量→ 不起作用
  • 我尝试返回获取的值
  • var a=firestore.collection(“collection1”).doc(“doc1”).get().then(){return doc.data().FIELD}

  • 从上面的列表中删除return关键字
  • 目前,我正在then()中执行类似console.log()的嵌套代码

    我的代码现在是什么样子

    var a = "BEFORE";
    console.log(a); // BEFORE
    firestore.collection("collection1").doc("doc1").then(
      function(doc) {
        const myData = doc.data();
        a = myData.Reciept_Series;
        console.log(a); // DESIRED_VALUE
      }
    )
    console.log(a); //BEFORE
    
    如何生成
    a=所需的_值
    ie.如何使用从FireStore获得的值


    提前感谢。

    在下面的代码中,Firebase一返回您的数据就会调用处理程序

    function handler(a) {
      // here you can work with a
    }
    
    firestore.collection("collection1").doc("doc1")
    .then(doc => doc.data)
    .then(myData => myData.Reciept_Series)
    .then(handler)
    .catch(console.error); // to debug: make sure the error (if any) is always reported
    
    如果要等待数据,请使用异步/等待模式:

    (async function() {
      var a = await firestore.collection("collection1").doc("doc1")
        .then(doc => doc.data)
        .then(myData => myData.Reciept_Series)
      // here you can work with a
    })();
    
    请记住,承诺(由
    then()
    返回)是异步运行的,因此您的代码不是按照自上而下的顺序执行的,而是作为另一个任务执行的

    您可以直接在顶层调用
    wait
    ,否则主线程将被它阻塞。请参见链接页面底部的支持表

    全局变量已分配,但是异步的。给代码一些时间,然后单击以下按钮:

    <button onclick="console.log(a)">Log data</button>
    
    日志数据
    
    问题不在于访问值的位置,而在于访问值的时间。控制台日志(a)在
    a=myData.receipt_系列之前在回调之外运行已运行,无法延迟。看到和