为什么在以下代码段中无法访问中的变量值

Why the variable value from is not accessible in following code snippet?

本文关键字:访问 变量值 段中无 代码 为什么      更新时间:2023-09-26

我有以下Javascript代码片段:

authData=ref.getAuth();
if(authData == null){
    //TODO find an elegant way to manage authorization 
    //  window.location = "../index.html";
} else {
      ref.child("users").child(authData.uid).on("value", function(snapshot){
      $( "span.user-name").html(snapshot.val().displayName);    
      loggedInUser.displayName = snapshot.val().displayName;
      //alert("Name inside : "+loggedInUser.displayName);
      //Here it displays the value      
    });         
}
alert("Nameada is out : "+loggedInUser.displayName);
//Here it shows 'undefined' 

为什么

我想使用变量值loggedInUser.displayName,我在哪里显示了警报。

有人能帮我访问值并显示警报吗?

谢谢。

当回调函数(function(snapshot){ ... })尚未调用时,将执行最终的alert。请注意,回调函数是异步调用的,因此它只有在当前运行的代码完成并触发value事件后才能执行。

这也解释了为什么内部(注释掉的)alert确实有效。只要意识到这段代码(回调函数)的执行时间比其他alert,即使它在代码中出现得更早。

你可以通过在回调中调用另一个函数来"解决"它,比如:

authData=ref.getAuth();
if(authData == null){
    //TODO find an elegant way to manage authorization 
    //  window.location = "../index.html";
} else {
    ref.child("users").child(authData.uid).on("value", function(snapshot){
        $( "span.user-name").html(snapshot.val().displayName);    
        loggedInUser.displayName = snapshot.val().displayName;
        whenUserLogged();
    });         
}
function whenUserLogged() {
   alert("Name : "+loggedInUser.displayName);
   // anything else you want to do....
}

一些改进建议

不要使用太多全局变量(在代码中,所有全局变量都是全局的),而是将变量作为函数参数传递。

你可能想看看承诺。