How to return value from firestore database?

*爱你&永不变心* 提交于 2021-02-08 11:28:26

问题


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?
        }

回答1:


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.

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

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.

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


来源:https://stackoverflow.com/questions/59537257/how-to-return-value-from-firestore-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!