首页 > 解决方案 > 异步函数设置变量

问题描述

我有个问题。 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

解决方案


推荐阅读