从 Firestore 获取异步值 [英] Get async value from firestore

查看:16
本文介绍了从 Firestore 获取异步值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为异步操作而苦苦挣扎.我试图简单地从 firestore 获取一个值并将其存储在一个 var 中.

I am struggling with async operations. I am trying to simply get a value from firestore and storing it in a var.

我设法接收到该值,我什至可以在我专门执行此操作时将其保存在 var 中(在 get 函数中使用 var),但是在尝试将其保存在灵活的方式:

I manage to receive the value, I can even save it in the var when I do that specifically (use the var within the get function) but I don't seem to manage the await properly when trying to save this in a flexible way:

async function getValues(collectionName, docName,) {
console.log("start")
var result;
var docRef = await db.collection(collectionName).doc(docName).get()
  .then(//async// (tried this as well with async) function (doc) {
    if (doc.exists) {
      console.log("Document data:", doc.data());
      result = doc.data().text;
      console.log(result);
      return //await// (this as well with async) result;
    } else {
      // doc.data() will be undefined in this case
      console.log("No such document!");
      result = "No such document!";
      return result;
    }
    console.log("end");
  }).catch (function (err) {
    console.log('Error getting documents', err);
  });
};

helpMessage = getValues('configuration','helpMessage');

注意:doc.data().text ->text" 是存储我的值的字段的名称.我必须在这里使用 .value 吗?

Note: doc.data().text -> "text" is the name of the field where my value is stored in. Do I have to use .value here?

我在控制台得到的结果是:

The result I get in the console is:

info: Document data: { text: 'The correct text from the database' }
info: 来自数据库的正确文本
info: Document data: { text: 'The correct text from the database' }
info: The correct text from the database

但是在我的代码中使用 helpMessage 我得到

But using helpMessage in my code I get

{}

来自 Telegram 机器人的图像,我试图在其中使用 helpMessage 作为对 '/help' 命令.

我已检查:从云防火墙中获取价值Firebase Firestore get() async/await, 从 firebase firestore 参考中获取异步值,最重要的是 如何从异步调用返回响应?.他们要么处理多个文档(使用 forEach),要么不解决我的问题的异步性质,要么(最后一种情况),我根本无法理解它的性质.

I have checked: getting value from cloud firestore, Firebase Firestore get() async/await, get asynchronous value from firebase firestore reference and most importantly How do I return the response from an asynchronous call?. They either deal with multiple documents (using forEach), don't address the async nature of my problem or (last case), I simply fail to understand the nature of it.

此外,nodejs 和 firestore 似乎都在快速发展,很难找到好的、最新的文档或示例.任何指针都非常有用.

Additionally, both nodejs and firestore seems to be developing rapidly and finding good, up-to-date documentation or examples is difficult. Any pointers are much appriciated.

推荐答案

您遇到了错误的方法.这比你想象的要容易得多.

You have things the wrong way around. It's much easier than you think it is.

function getValues(collectionName, docName) {
    return db.collection(collectionName).doc(docName).get().then(function (doc) {
        if (doc.exists) return doc.data().text;
        return Promise.reject("No such document");
    }};
}

如果一个函数返回一个promise(比如db.collection(...).doc(...).get()),返回那个promise.这是上面的外部"return.

If a function returns a promise (like db.collection(...).doc(...).get()), return that promise. This is the "outer" return above.

在 promise 处理程序中(在 .then() 回调中),返回一个值来表示成功,或者返回一个被拒绝的承诺来表示一个错误.这是上面的内部"return.如果你愿意,你也可以throw一个错误,而不是返回一个被拒绝的承诺.

In the promise handler (inside the .then() callback), return a value to indicate success, or a rejected promise to indicate an error. This is the "inner" return above. Instead of returning a rejected promise, you can also throw an error if you want to.

现在你有了一个返回 promise 的函数.您可以将它与 .then().catch() 一起使用:

Now you have a promise-returning function. You can use it with .then() and .catch():

getValues('configuration','helpMessage')
    .then(function (text) { console.log(text); })
    .catch(function (err) { console.log("ERROR:" err); });

await 在 try/catch 块中的 async 函数中,如果你更喜欢它:

or await it inside an async function in a try/catch block, if you like that better:

async function doSomething() {
    try {
        let text = await getValues('configuration','helpMessage');
        console.log(text);
    } catch {
        console.log("ERROR:" err);
    }
}

<小时>

如果您想在 getValues() 函数中使用 async/await,您可以:


If you want to use async/await with your getValues() function, you can:

async function getValues(collectionName, docName) {
    let doc = await db.collection(collectionName).doc(docName).get();
    if (doc.exists) return doc.data().text;
    throw new Error("No such document");
}

这篇关于从 Firestore 获取异步值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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