2016-12-25 105 views
0

圣诞快乐/节日快乐!我试图从使用js/firebase的函数中获取变量,并在另一个函数中使用所述变量。问题在于b/c firebase是异步的,该变量在需要运行的功能之后加载。我的代码如下。在JS/FIREBASE中获取变量的问题异步执行

我的问题:如何在执行loadMessages()之前从initChatroom()中获取convoId?

// Global Variable 
var convoId = ''; 

// Triggers when the auth state change for instance when the user signs-in or signs-out. 
MyApp.prototype.onAuthStateChanged = function(user) { 
    if (user) { // User is signed in! 

    // We load currently existing chat messages. 
    this.initChatRoom(); 
    this.loadMessages(); 
    } 
}; 

//Get chatroom name 
MyApp.prototype.initChatRoom = function(){ 

    var userId = this.auth.currentUser.uid; 
    return this.database.ref('/user_profiles/' + userId).once('value').then(function(snapshot) { 
    var agentAssigned = snapshot.val().agent_assigned; 

    //Gets Chatroom details 
    if (snapshot.hasChild("agent_assigned")){ 

     userNameExtract = snapshot.val().nickname; 

    //First five user & first five counterparty 
     var receieverID = agentAssigned; 
     var senderId = userId; 
     var receiverIDFive = receieverID.substring(0,5); 
     var senderIdFive = senderId.substring(0,5); 

     if (senderIdFive > receiverIDFive){ 

      convoId = senderIdFive + receiverIDFive; 
     } 
     else{ 
      convoId = receiverIDFive + senderIdFive; 
     } 

     console.log("chatroom name", convoId); 
    } 
    else{ } 
    }); 

} 

// Loads chat messages history and listens for upcoming ones. 
MyApp.prototype.loadMessages = function() { 

    console.log("loadMessage", convoId); //CONVO ID is not loaded yet :(

    this.messagesRef = this.database.ref('messages/' + convoId + '/'); 

    // Make sure we remove all previous listeners. 
    this.messagesRef.off(); 

    // Loads the last 12 messages and listen for new ones. 
    var self = this; 
    // Loads the last 12 messages and listen for new ones. 
    var setMessage = function(data) { 

    var dataVar = data.val(); 

    self.displayMessage(data.key, dataVar.userName, dataVar.text, dataVar.type, dataVar.senderId); 
    }; 

    this.messagesRef.limitToLast(12).on('child_added', setMessage); 
    this.messagesRef.limitToLast(12).on('child_changed', setMessage); 
}; 
+0

如果第二个函数依赖于第一个函数的执行,那么为什么不在那里调用它(例如:在数据库查询的回调函子中)? – UnholySheep

+0

我曾试过这个,但我一直得到“未捕获(承诺)TypeError:无法读取未定义的属性'loadMessages' – gk103

+0

在这种情况下,您可能在右大括号后面缺少'.bind(this)' (快照){// code} .bind(this)'应该可以)。或者你应该使用ES6脂肪箭头功能自动完成 – UnholySheep

回答

1

所以按照意见:

由于功能loadMessages取决于功能initChatRoom应该从那里被调用的结果,回调函子到数据库调用内(返回所需数据)。然而这个仿函数需要绑定到正确的范围内,因此它被定义为:使用ES6“胖箭头”

this.database.ref('/user_profiles/' + userId).once('value').then(function(snapshot) { 
    // operations on data 
    this.loadMessages() 
}.bind(this) 

另外,语法就可以写成:

this.database.ref('/user_profiles/' + userId).once('value').then((snapshot) => { 
    // operations on data 
    this.loadMessages() 
}