[英]Javascript scope not updating global variable
I'm sitting in my js file trying to upload but for some reason, I don't understand entirely.我坐在我的 js 文件中尝试上传,但由于某种原因,我完全不明白。 My :: myUid isn't updating.我的 :: myUid 没有更新。 Can anyone tell me how to fix it and maybe even why it's the case that myUid isn't updating?谁能告诉我如何修复它,甚至为什么 myUid 没有更新?
var myUid = '33';
firebase.auth().signInAnonymously().catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
window.myUid = user.uid;
// ...
} else {
// User is signed out.
// ...
}
// ...
});
function writeUserData() {
database.ref('users/').set({
profileID: myUid,
});
};
writeUserData();
Best regards, Sam最好的问候,山姆
myUid
value is updated only when the callback for onAuthStateChanged
is executed asynchronously . myUid
值仅在onAuthStateChanged
的回调异步执行时更新。 By the time you invoke the writeUserData()
function on your main execution flow, the above callback may not be have been completed yet.当您在主执行流程上调用writeUserData()
函数时,上述回调可能尚未完成。
So a better approach would be to get rid of the global variable and invoke the writeUserData
function from the onAuthStateChanged
callback, passing the user uid as a parameter.所以更好的方法是去掉全局变量并从onAuthStateChanged
回调调用writeUserData
函数,将用户 uid 作为参数传递。
function writeUserData(userUid) {
database.ref('users/').set({
profileID: userUid,
});
};
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
writeUserData(user.uid);
// ...
} else {
// User is signed out.
// ...
}
// ...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.