2016-12-25 110 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() 
}