如何在Firebase Firestore中获取单个文档数据(无承诺) [英] How to get a single document data in a Firebase Firestore (without promises)

查看:49
本文介绍了如何在Firebase Firestore中获取单个文档数据(无承诺)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im试图获取单个文档的数据并将其保存到变量中,以供以后在另一个逻辑操作中使用.Firestore文档显示仅使用promise即可做到这一点,但是我无法将doc.data()值设置为变量以供以后使用,仅在then()或catch()方法内部.我可以在那里设置变量,但是不能在promise之外使用它.

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. I can set a variable there but i can't use it outside the promise.

Firestore文档示例:

Firestore documentation example:

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

推荐答案

正如Jaromanda X所说:您最好接受Firebase和大多数现代Web的异步特性.您越早掌握编程模式,就越早可以恢复这种范例的生产力.

As Jaromanda X commented: you're best of accepting the asynchronous nature of Firebase and most of the modern 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.

这篇关于如何在Firebase Firestore中获取单个文档数据(无承诺)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆