我正在尝试实现一个功能,以给定ID检查我的FireStore数据库中是否存在文档。问题是我的fire_PatronExists函数始终返回undefined

const patronsRef = db.collection("patrons");

alert(fire_PatronExists(user.uid));

function fire_PatronExists(id) {

    patronsRef.doc(id).get().then(function(doc) {
        // return doc.exists();
        if (doc){return true}else {return false}
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
}

最佳答案

函数返回未定义的事实是完全正常的:get()是异步方法,因此放在then内部的返回将不会在fire_PatronExists内部执行;它将在稍后执行。有一个great SO article解释了同步执行和异步执行之间的区别。

有不同的解决方案,具体取决于您使用的JavaScript版本。可以肯定使用的方法是将回调函数传递给fire_PatronExists并将结果传递给该函数。

看起来像这样(未经测试):

const patronsRef = db.collection("patrons");

fire_PatronExists(user.uid, function(exists) {
    alert(exists);
});

// Remember though, if you put code here, it will be executed in parallel
// with the code you put inside your callback.

function fire_PatronExists(id, callback) {

    patronsRef.doc(id).get().then(function(doc) {

    }).catch(function(error) {
        console.log("Error getting document:", error);
    });
}


使用回调可能会变得非常混乱。如果您使用的是最新版本的JavaScript,则可能需要read about asyncawait关键字,它们可以大大提高代码的可读性。

10-05 20:54
查看更多