[英]Pulling a variable out of Promise when querying data from Firestore Firebase database - Javascript
[英]Javascript execution order when pulling Firebase data
在使用Google auth向Firebase進行身份驗證之后,我得到了console.log
輸出,並且JavaScript似乎按執行順序反彈。 這是我的控制台輸出和javascript代碼。
為什么“ controller is:Pellet_Pirate_1”在日志末尾而不是在執行代碼以從Firebase提取此值的開始處顯示? 我的“ GLOBAL CONTROLLER”和contr
全局變量的其他日志也應該被賦值...我試圖將contr
用作全局變量,它在我的腳本標簽的頂部定義
任何幫助將不勝感激...我已經為此努力了很多小時!
<script type="text/javascript">
var contr = undefined;
function PelletPirate() {
this.userPic = document.getElementById('user-pic');
this.userName = document.getElementById('user-name');
this.signInButton = document.getElementById('sign-in');
this.signOutButton = document.getElementById('sign-out');
this.signOutButton.addEventListener('click', this.toggleSignOut.bind(this));
this.signInButton.addEventListener('click', this.toggleSignIn.bind(this));
this.initFirebase();
}
// Sets up shortcuts to Firebase features and initiate firebase auth.
PelletPirate.prototype.initFirebase = function() {
//FlymanEdit Shortcuts to Firebase SDK features.
this.auth = firebase.auth();
this.database = firebase.database();
this.storage = firebase.storage();
//FlymanEdit Initiates Firebase auth and listen to auth state changes.
this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
};
PelletPirate.prototype.toggleSignIn = function() {
var provider = new firebase.auth.GoogleAuthProvider(); // [Start createprovider]
provider.addScope('https://www.googleapis.com/auth/plus.login'); // [START addscopes]
this.auth.signInWithPopup(provider).then(function(result)
{
var token = result.credential.accessToken;
var user = result.user;
console.log('token: ' + token);
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential; // The firebase.auth.AuthCredential type that was used.
if (errorCode === 'auth/account-exists-with-different-credential') {
alert('You have already signed up with a different auth provider for that email.');
}
else {
console.error(error);
}
});
}
// Sign-out.
PelletPirate.prototype.toggleSignOut = function() {
this.auth.signOut();
console.log('******************** USER SIGNED OUT *********************');
};
PelletPirate.prototype.onAuthStateChanged = function(user) { // Triggers when user's auth state changes.
if (user) { // User is signed in!
// let's go fetch the Pellet Pirate controller name based on the logged in user!
console.log('user.uid is: ' + user.uid);
firebase.database().ref().child("owners").orderByChild("userId").equalTo(user.uid).on('value', function (snapshot) {
snapshot.forEach(function(childSnapshot) {
contr = childSnapshot.val().controller;
//MYLIBRARY.init([controller, 1, "controller"]);
//MYLIBRARY.passVar();
console.log('controller is: ' + contr);
return contr;
});
});
var currentDate = new Date();
var profilePicUrl = user.photoURL;
var userName = user.displayName;
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var refreshToken = user.refreshToken;
var providerData = user.providerData;
//console.log('You have signed in: ' + userName );
console.log('*************** signed in: ' + userName + ' *****************');
console.log('GLOBAL CONTROLLER: ' + contr);
document.getElementById('authed').style.visibility = 'visible';
document.getElementById('authed2').style.visibility = 'visible';
document.getElementById('gauges').style.visibility = 'visible';
document.getElementById('graph').style.visibility = 'visible';
document.getElementById('parameters').style.visibility = 'visible';
document.getElementById('ParmForm').style.visibility = 'visible';
document.getElementById('ClearDataButton').style.visibility = 'visible';
document.getElementById('AddProgramButton').style.visibility = 'visible';
document.getElementById('programrows').style.visibility = 'visible';
// Set the user's profile pic and name.
this.userPic.style.backgroundImage = 'url(' + profilePicUrl + ')';
this.userName.textContent = userName;
// Show user's profile and sign-out button.
this.userName.removeAttribute('hidden');
this.userPic.removeAttribute('hidden');
this.signOutButton.removeAttribute('hidden');
// Hide sign-in button.
this.signInButton.setAttribute('hidden', 'true');
console.log('before firebase controller is: ' + contr);
//controllerName = "Pellet_Pirate_1";
//Firebase
var TempsRef = Ref.child('ControllerData/' + contr + '/Temps');
console.log('after firebase controller is: ' + contr);
TempsRef.limitToLast(3600/3*16).once("value", function(snapshot) { //Limit to last 16 hours
var Ts = snapshot.val();
for (var k in Ts) {
T1.push([Ts[k].time, Ts[k].T1]);
T2.push([Ts[k].time, Ts[k].T2]);
T3.push([Ts[k].time, Ts[k].T3]);
TT.push([Ts[k].time, Ts[k].TT]);
console.log('in snapshot');
}
TempsRef.limitToLast(1).on("child_added", function(snapshot, prevChildKey) { //Establish callback
var Ts = snapshot.val();
T1.push([Ts.time, Ts.T1]);
T2.push([Ts.time, Ts.T2]);
T3.push([Ts.time, Ts.T3]);
TT.push([Ts.time, Ts.TT]);
UpdatePlot();
console.log('in snapshot-previousChildKey' );
//console.log('in snapshot-PCK-controllerName is:' + controllerName);
});
UpdatePlot();
});
TempsRef.on("child_removed", function(snapshot, prevChildKey) {
T1 = [];
T2 = [];
T3 = [];
TT = [] ;
UpdatePlot();
});
}
else { // User is signed out!
// Hide user's profile and sign-out button.
this.userName.setAttribute('hidden', 'true');
this.userPic.setAttribute('hidden', 'true');
this.signOutButton.setAttribute('hidden', 'true');
document.getElementById('authed').style.visibility = 'hidden';
document.getElementById('authed2').style.visibility = 'hidden';
document.getElementById('gauges').style.visibility = 'hidden';
document.getElementById('graph').style.visibility = 'hidden';
document.getElementById('parameters').style.visibility = 'hidden';
document.getElementById('ParmForm').style.visibility = 'hidden';
document.getElementById('ClearDataButton').style.visibility = 'hidden';
document.getElementById('AddProgramButton').style.visibility = 'hidden';
document.getElementById('programrows').style.visibility = 'hidden';
// Show sign-in button.
this.signInButton.removeAttribute('hidden');
// undefine the controller
contr = undefined;
}
}; // [ END onAuthStateChanged - auth state listener]
因為on()
是異步的。 查詢在后台進行時,它將立即返回。 同時,緊隨其后的代碼將一直運行到首次提供給您的回調調用結果快照時為止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.