javascript - 无法从 firebase.auth().signInWithPopup(provider) 函数中更改变量

标签 javascript firebase firebase-authentication

所以我定义了一个名为 testVariable 的变量并将其设置为 initial$scope.signIn () 函数。然后在 firebase.auth().signInWithPopup(provider).then() 函数中,我将其更改为 changed。当我在 firebase.auth().signInWithPopup(provider).then() 之外的 console.log()> 返回 initial 的函数。我希望它返回 changed,下面的代码有什么问题?任何帮助将不胜感激。

var app = angular.module("myApp", []);

app.controller("MainController", ["$scope", function ($scope){
    $scope.googleSignInStyle = {};
    $scope.googleSignInText = "";
    $scope.signIn = function (){
        var provider = new firebase.auth.GoogleAuthProvider();
        var testVariable = "initial";

        firebase.auth().signInWithPopup(provider).then(function(result) {
            var token = result.credential.accessToken;
            var user = result.user;
            var providerData = user.providerData[0];

            firebase.database().ref('users/' + providerData.displayName).set({Email: providerData.email, PhotoURL: providerData.photoURL, uid: providerData.uid});

            testVariable = "changed";

        }).catch(function(error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            var email = error.email;
            var credential = error.credential;
            console.log ("Error! Error code: " + errorCode + ", Email: " + email + ", Credential: " + credential + ". That's all we know.");
        });

        console.log (testVariable);
    }
}]);

最佳答案

您对 .then() 的调用异步运行。这意味着它会在稍后返回 firebase.auth().signInWithPopup(provider) 时运行。

因此,您实际上是在更改 testVariable 的值,但是是在打印出来之后。换句话说,.then() 内部发生的事情发生在你调用 console.log(testVariable) 之后

如果你不熟悉 promise 的概念read this .

关于javascript - 无法从 firebase.auth().signInWithPopup(provider) 函数中更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38398401/

相关文章:

ios - 无法在已安装的 Firebase 组件中使用 Carthage 安装 FirebaseAuth

javascript - 刷新网页时 Firebase 当前用户未定义

javascript - 取消/停止超时功能

javascript - 是否可以从其自己的处理程序对象中引用代理?

angularjs - 使用 firebase 获取当前用户的 Angular ?

ios - 将名字和姓氏从 Gmail 帐户发布到 Firebase

javascript - 从 2 个按 id 分组的 JSON 对象创建新的 javascript 对象

javascript - Node.js 获取访问 token

javascript - Firebase:更改服务 worker 的位置

ssl - 带有 Firebase 的 Telit GE910 SSL 协议(protocol)