提取Firebase数据时的JavaScript执行顺序

时间:2018-07-02 00:03:39

标签: javascript firebase firebase-realtime-database firebase-authentication

我使用Google auth向Firebase进行身份验证后,得到了console.log输出,并且JavaScript似乎按执行顺序反弹。这是我的控制台输出和javascript代码。

为什么“ controller is:Pellet_Pirate_1”显示在日志末尾而不是在执行代码以从Firebase提取此值的开始处?我的“ GLOBAL CONTROLLER”和contr全局变量的其他日志也应该被赋值...我正在尝试使用contr作为全局变量,它在我的脚本标签的顶部定义

任何帮助将不胜感激……我已经为此努力了很多小时!

https://developer.wordpress.org/themes/template-files-section/page-template-files/

<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]

1 个答案:

答案 0 :(得分:1)

因为on()是异步的。查询在后台进行时,它将立即返回。同时,紧随其后的代码将一直运行到第一次提供给您的回调并带有结果快照时为止。