如何从Firestore数据库返回值? [英] How to return value from firestore database?

查看:83
本文介绍了如何从Firestore数据库返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难从Firestore数据库返回值.我正在尝试从数据库中返回金额".设置变量时,我可以console.log'amount'.(请参见代码)但是当我尝试在函数末尾返回值时,它不返回任何东西.('amount'未定义no-undef)我如何返回该值.任何帮助将是巨大的.请记住,我对这个话题还很陌生.

I am having a hard time returning a value from the firestore database. I am trying to return the 'amount' from the database. When setting the variable i am able to console.log the 'amount'. (see code) But when i try to return the value at the end of the function, it does not return anything.('amount' is not defined no-undef) How can i return this value. Any help would be great. Please keep in mind that i am still quite new to this topic.

        import firebase from 'firebase/app';
        import 'firebase/firestore';
        import 'firebase/auth';

        export default function checkAmount() {

            let user = firebase.auth().currentUser;

            if (user) {
                let userUID = user.uid
                let docRef = firebase.firestore().collection("users").doc(userUID);

                docRef.get().then((doc) => {
                    if (doc.exists) {
                            let amount = doc.data().amount;
                            if (amount > 0){
                                console.log(amount) /// This does work
                            }
                        } else {
                            console.log("No such document!");
                        }
                    }).catch(function(error) {
                        console.log("Error getting document:", error);
                    });
            }

            return amount /// This **does not** return anything . How do i return the amount?
        }

推荐答案

原因是因为 get()方法是异步的:它立即返回并带有解决 some 的承诺.em>时间之后再查询结果. get()方法不会阻止该函数(如上所述,它会立即返回):这就是为什么在异步工作之前执行最后一行(返回量)的原因已完成,但具有未定义的值.

The reason is because the get() method is asynchronous: it returns immediately with a promise that resolves some time later with the results of the query. The get() method does not block the function (it returns immediately, as said above): this is why the last line (return amount) is executed before the asynchronous work is finished but with an undefined value.

您可以在此处阅读更多内容>关于异步JavaScript方法和此处说明为什么Firebase API是异步的.

You can read more here on asynchronous JavaScript methods and here on why Firebase APIs are asynchronous.

因此,您需要等待 get()返回的promise解析并使用Alex提到的 then()方法来接收查询结果并发送响应.

You therefore need to wait that the promise returned by the get() resolves and use the then() method, as Alex mentioned, to receive the query results and send the response.

以下将起作用:

    export default function checkAmount() {

        let user = firebase.auth().currentUser;

        if (user) {
            let userUID = user.uid
            let docRef = firebase.firestore().collection("users").doc(userUID);

            return docRef.get().then((doc) => {  //Note the return here
                if (doc.exists) {
                        let amount = doc.data().amount;
                        if (amount > 0){
                            console.log(amount) /// This does work
                            return true;  //Note the return here
                        }
                    } else {
                        console.log("No such document!");
                        //Handle this situation the way you want! E.g. return false or throw an error
                        return false;
                    }
                }).catch(error => {
                    console.log("Error getting document:", error);
                    //Handle this situation the way you want
                });
        } else {
           //Handle this situation the way you want
        }

    }

但是您需要注意,您的功能现在也异步了.因此,您应按以下方式调用它:

But you need to note that your function is now also asynchronous. Therefore you should call it as follows:

checkAmount().
then(result => {
  //Do whatever you want with the result value
  console.log(result);
})

这篇关于如何从Firestore数据库返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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