[英]How to get a single document data in a Firebase Firestore (without promises)
im trying to get the data of a single document and save it to a variable for use it later in another logic operation. 我试图获取单个文档的数据并将其保存到变量中,以供以后在另一个逻辑操作中使用。 The firestore documentation show hot to do this only with promises but i can't set the doc.data() value to a variable for later use, only inside the then() or catch() method.
Firestore文档显示仅使用promise即可做到这一点,但我无法将doc.data()值设置为变量以供以后使用,仅在then()或catch()方法内部。 I can set a variable there but i can't use it outside the promise.
我可以在那里设置变量,但是不能在诺言之外使用它。
Firestore documentation example: Firestore文档示例:
var docRef = db.collection("cities").doc("SF");
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
As Jaromanda X commented: you're best of accepting the asynchronous nature of Firebase and most of the modern web. 正如Jaromanda X所说:您最好接受Firebase和大多数现代Web的异步特性。 The sooner you get to grips with the programming patterns, the sooner you can get back to being productive in this paradigm.
您越早掌握编程模式,就越早可以恢复这种范例的生产力。
I find it most helpful to reframe problems. 我发现重新构造问题最有帮助。 Instead of "Load a document, then do something with it" I frame it as "First start loading a document. Once the document has loaded, do something with it".
我将其构架为“首先开始加载文档。加载文档后,对其进行操作”,而不是“加载文档,然后对其进行处理”。
In practice that means that you move your code that needs the document into the completion handler where you now have the logging statements. 实际上,这意味着您将需要文档的代码移动到完成处理程序中,在该处理程序中现在有了日志记录语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.