如何从firestore数据库返回值?

San*_*uel 2 javascript firebase google-cloud-firestore

我很难从 Firestore 数据库中返回一个值。我正在尝试从数据库中返回“金额”。设置变量时,我可以在 console.log 中记录“金额”。(请参阅代码)但是当我尝试在函数末尾返回值时,它不返回任何内容。('amount' 未定义 no-undef)我如何返回此值。任何帮助都会很棒。请记住,我对这个话题还是很陌生。

        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?
        }
Run Code Online (Sandbox Code Playgroud)

Ren*_*nec 6

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

你可以阅读更多这里异步JavaScript方法和这里为什么火力地堡的API是异步的。

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

以下将起作用:

    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
        }

    }
Run Code Online (Sandbox Code Playgroud)

但是您需要注意您的函数现在也是异步的。因此,您应该按如下方式调用它:

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