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);
};
:それはのように書くことができ構文ES6「脂肪矢印」を使用して、代わりに
:しかし、このファンクタは、それがのように定義する必要がありますので、正しいコンテキストにバインドする必要があります2番目の関数は最初の関数の実行に依存していますが、そこではそれを呼び出さないでください(例:データベースクエリのコールバック関数で)。 – UnholySheep
私はこれを試していましたが、 "Uncaught(約束しています)"を続けていますTypeError:未定義の 'loadMessages'プロパティを読み込めません " – gk103
その場合、閉じ括弧の後ろにおそらく' .bind(this) (スナップショット){//コード} .bind(これ) 'が動作するはずです)。または、これを自動的に実行するには、ES6太鼓の機能を使用する必要があります – UnholySheep