javascript - 异步函数设置变量
问题描述
我有个问题。
docRef.get().then(...)
是一个异步工作的函数。由于它立即返回,因此不会设置用户名。我怎样才能获得值并将其设置为变量username
?
var username;
var kontostand;
var ticket;
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
// User is signed in.
document.getElementById("user_div").style.display = "block";
document.getElementById("login_div").style.display = "none";
var docRef = db.collection("users").doc(user.uid);
// Get the data from the user
docRef.get().then(function (doc) {
if (doc.exists) {
//console.log("Document data:", doc.data());
kontostand = doc.data().kontostand;
ticket = doc.data().ticket;
username = doc.data().username;
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function (error) {
console.log("Error getting document:", error);
});
var user = firebase.auth().currentUser;
if (user != null) {
document.getElementById("user_para").innerHTML = "Welcome User : " + username;
}
解决方案
推荐阅读
- javascript - firebase 令牌对每个用户来说都是唯一且永久的吗?
- python-3.x - 使用烧瓶 sqlalchemy 进行多处理 - psycopg2.DatabaseError:状态为 PGRES_TUPLES_OK 的错误并且没有来自 libpq 的消息
- python - 手动更新 matplotlib 动画
- python-3.x - 如何使用opencv将阈值计数器仅应用于图像中的指定/屏蔽区域
- python - 无法使用 Python 中的密钥解密文件
- java - 如何将存储在 mongodb 中的 getter 方法用于其他 POJO 类?
- kotlinpoet - 创建扩展函数(名称中带有 . 的函数)
- javascript - 循环使用 FileReader 仅显示 div 网格中的最后一个图像
- excel - 如何访问 VBA 中数据透视表的特定列总计?
- javascript - 循环中的字符串数组值