【问题标题】:Cannot get data from class method taken from Firebase无法从从 Firebase 获取的类方法中获取数据
【发布时间】:2019-07-08 15:28:53
【问题描述】:

我很难解决我的问题。我已连接到 Firebase,并尝试设置连接并检查名称是否在数据库中。

 class Db {

    connect (path) {
        const db = firebase.firestore();
        const docRef = db.doc(path);
        return docRef;
    }

    exist (name, path) {

        this.connect(path).get()
        .then(querySnapshot => {
            console.log(querySnapshot.data().Users);
            const users = querySnapshot.data().Users;
            // return users;
            if (users.indexOf(name) > -1) {
                console.log('yes');
                return true
            } else {
                console.log('no');
                return false
            }
        })
        .catch(e => {
            console.log(e);
        })
    }
}


let databaseurl = '2048/database';
let database = new Db();

console.log(database.exist('kytek', databaseurl));  //undefined

从控制台日志我得到undefined 但控制台日志返回一个数组,我不知道为什么...... 在 if 之前加上 return 部分:

console.log(querySnapshot.data().Users);
const users = querySnapshot.data().Users;
return users;

并且 consol.log 返回数组 但是return 返回undefined 有任何想法吗?

【问题讨论】:

    标签: javascript database firebase google-cloud-firestore database-connection


    【解决方案1】:

    你没有得到你的真/假值,因为你写的exist() 函数是异步的,你没有返回内部函数。如果你想从内部this.connect().get()函数返回数据,你需要返回那个外部函数……我的意思是:

    exist (name, path) {
    
        return this.connect(path).get()
            .then(querySnapshot => {
            // etc... rest of function here
    

    如果这对您不起作用,您可能还必须将该函数标记为 async 并使用 await 等待接收结果:

    async exist (name, path) {
    
        return this.connect(path).get()
            .then(querySnapshot => {
            // etc... rest of function here
    
    
    let databaseurl = '2048/database';
    let database = new Db();
    
    let result = await database.exist('kytek', databaseurl);
    console.log(result);
    

    【讨论】:

    • 您的第一个解决方案有效,我不是简单的错误或正确,而是Promise {<pending>} __proto__: Promise [[PromiseStatus]]: "resolved" [[PromiseValue]]: false
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 2019-08-10
    相关资源
    最近更新 更多