Reputation: 301
I am trying to implement a function to check if a doc exists in my FireStore database, given an id. The problem is my fire_PatronExists
function always return 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);
});
}
Upvotes: 2
Views: 1465
Reputation: 1675
The fact that your function returns undefined is totally normal: get()
is an asynchronous method, so the return you put inside the then
will not be executed inside fire_PatronExists
; it will be executed a bit later. There is a great SO article that explains the difference between synchronous and asynchronous execution.
There are different solutions, depending on the version of JavaScript you are using. One that will work for sure is passing a callback function to fire_PatronExists
and pass the result to that function.
This would look like that (not tested):
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);
});
}
Using callbacks can get really messy though. If you are using a recent version of JavaScript, you might want to read about the async
and await
keywords, they can improve your code readability a lot.
Upvotes: 4