在JS / FIREBASE异步执行中获取变量的问题

时间:2016-12-25 19:06:12

标签: javascript firebase firebase-realtime-database

圣诞快乐/节日快乐!我试图从使用js / firebase的函数中获取变量,并在另一个函数中使用该变量。问题是b / c 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);
};

1 个答案:

答案 0 :(得分:1)

根据评论:

由于函数loadMessages依赖于函数initChatRoom的结果,因此应该从回调函数中调用它到数据库调用(返回所需的数据)。但是,这个仿函数需要绑定到正确的上下文,因此必须将其定义为:

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

或者,使用ES6“胖箭头”语法,它可以写成:

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