我正在重构一些代码,以便不同js文件中的不同javascript模块可以使用相同的Firebase实例。我还想在不同的模块加载时消除竞争条件的可能性。
我相信这些是我需要遵循的步骤,以避免竞争条件:
在代码中,这将大致转换为以下内容:
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="crossorigin="anonymous"></script>
<script src="https://www.gstatic.com/firebasejs/3.6.1/firebase.js"></script>
<script type="text/javascript">
if (firebase.apps.length === 0) {
firebase.initializeApp({
apiKey: "<REMOVED>",
authDomain: "<REMOVED>",
databaseURL: "<REMOVED>",
storageBucket: "<REMOVED>",
messagingSenderId: "<REMOVED>"
});
}
firebase.auth().signOut().then(function () {
var customTokenUrl = "<REMOVED>";
$.ajax({
url: customTokenUrl,
data: {},
xhrFields: {withCredentials: true},
crossDomain: true,
success: function (token) {
firebase.auth().signInWithCustomToken(token);
},
type: 'POST'
});
});
</script>
<script src="someurl/module1.js"></script>
<script src="someurl/module2.js"></script>
这大致是module1.js和module2.js的代码:
var module1 = (function (MODULE) {
...
...
firebase.auth().onAuthStateChanged(MODULE.onAuthStateChanged.bind(MODULE));
function onAuthStateChanged(user) {
if (user) {
// User is signed in.
MODULE.uid = user.uid;
setWatchers(); // This is where I set the firebase refs
}
}
return MODULE;
}
以下是我的问题:
onAuthStateChanged
是否有可能无法触发?我认为,理论上,module1.js可以在firebase中更改auth状态后执行。这不会导致onAuthStateChanged
方法无法启动吗?firebase
吗?