我正在开发 Angular 应用程序,想从 Firestore 获取一些数据。但是我的函数总是返回 undefined
。但是,当我 console.log()
返回值之前,它会显示正确的值。
getToken(user_id) {
this.afs.collection("tokens").ref.doc(user_id).get().then((doc) => {
if (doc.exists) {
console.log(doc.data().user_token); //displays the correct user_token value
return doc.data().user_token; //returns undefined!
}
});
}
两个值不应该相同吗?
最佳答案
看来您没有从函数中返回 Promise
- getToken
函数中根本没有 return 语句,因此函数本身只返回 未定义
。您拥有的内部返回声明将解决 promise ,这很好,但您必须处理该解决方案。
如果你像这样返回 promise :
getToken(user_id) {
return this.afs.collection("tokens").ref.doc(user_id).get().then((doc) => {
if (doc.exists) {
console.log(doc.data().user_token); //displays the correct user_token value
return doc.data().user_token;
}
});
}
当 promise 通过执行以下操作解决时,您应该能够异步访问 user_token
:
getToken(user_id).then(user_token => {
handle_user_token_here(user_token);
});
注意:修改后的函数将返回一个 promise 。因此,您不能简单地执行以下操作:
let user_token = getToken(user_id);
// user_token here is a Promise object, not the token!
handle_user_token_here(user_token); // will not work.
不过你可以这样做:
let user_token = getToken(user_id);
// user_token here is a Promise object, not the token!
user_token.then(user_token => handle_user_token_here(user_token)); // will work
关于javascript - console.log() 显示正确的值,但是当将其分配给变量时,它是未定义的 - Angular,firestore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56365265/