我很难从 firestore 数据库返回值。 我正在尝试从数据库返回“金额”。 设置变量时,我可以 console.log '金额'。 (见代码) 但是当我尝试返回函数末尾的值时,它不会返回任何内容。(“金额”未定义 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?
}
最佳答案
原因是 get()
方法是异步的:它立即返回并带有一个 Promise,该 Promise 会在一段时间后解析查询结果。 get()
方法不会阻塞函数(它立即返回,如上所述):这就是为什么最后一行(return amount
)在异步工作之前执行的原因已完成,但具有未定义的值。
您可以阅读更多here关于异步 JavaScript 方法和 here为什么 Firebase API 是异步的。
因此,您需要等待 get()
返回的 Promise 解析并使用 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
}
}
但您需要注意,您的函数现在也是异步的。因此,您应该按如下方式调用它:
checkAmount().
then(result => {
//Do whatever you want with the result value
console.log(result);
})
关于javascript - 如何从firestore数据库返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59537257/