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

查看:70
本文介绍了从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),但是尝试将其保存在a中时,我似乎无法正确地管理await灵活的方式:

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->文本" 是存储我的值的字段的名称.在这里我必须使用 .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:数据库中的正确文本
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'命令.

我已检查:从云Firestore获取价值 Firebase Firestore get()async/await .他们要么处理多个文档(使用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");
    }};
}

如果一个函数返回一个承诺(例如 db.collection(...).doc(...).get()),则返回该承诺.这是上面的外部" 返回.

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

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

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.

现在,您已经有了一个兑现承诺的功能.您可以将其与 .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); });

在try/catch块中的 async 函数中

await ,如果您更喜欢:

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天全站免登陆