我想从Firebase FireStore→中获取数据(文档中的一个特定字段),将该值分配给全局变量→console.log这个值。
我的研究到现在为止:
var a = firestore.collection("collection1").doc("doc1").get().then(){ return doc.data().FIELD}
目前,我正在执行如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 = DESIRED_VALUE
呢?如何使用从FireStore获得的值。
提前谢谢。
发布于 2021-05-14 13:52:22
在下面的代码中,一旦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()
返回)是运行then()
的,因此您的代码不是按自顶向下的顺序执行,而是作为另一个任务执行。
您可以在顶层只在await
中调用模块,否则主线程将被其阻塞。请参阅链接页底部的支持表。
您的全局变量是分配的,但是是异步的。给代码一些时间,然后单击以下按钮:
<button onclick="console.log(a)">Log data</button>
https://stackoverflow.com/questions/67535334
复制相似问题