简体   繁体   English

如何从firestore数据库返回值?

[英]How to return value from firestore database?

I am having a hard time returning a value from the firestore database.我很难从 Firestore 数据库中返回一个值。 I am trying to return the 'amount' from the database.我正在尝试从数据库中返回“金额”。 When setting the variable i am able to console.log the 'amount'.设置变量时,我可以在 console.log 中记录“金额”。 (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. (请参阅代码)但是当我尝试在函数末尾返回值时,它不返回任何内容。('amount' 未定义 no-undef)我如何返回此值。 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?
        }

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.原因是因为get()方法是异步的:它立即返回一个承诺,该承诺在一段时间后用查询结果解析。 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. get()方法不会阻塞函数(它会立即返回,如上所述):这就是为什么在异步工作完成之前执行最后一行( return amount )但具有未定义的值。

You can read more here on asynchronous JavaScript methods and here on why Firebase APIs are asynchronous.你可以阅读更多这里异步JavaScript方法和这里为什么火力地堡的API是异步的。

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.因此,您需要等待get()返回的承诺解析并使用then()方法,正如 Alex 提到的那样,接收查询结果并发送响应。

The following will work:以下将起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM