我有此代碼,我只需要返回一個uid,以便以后可以使用Id進行Firestore操作$(document).ready(function () { var uid; auth.onAuthStateChanged(function (user) { if (user != null) { uid = user.uid; console.log(typeof uid)//returns a string ; } }); console.log(uid); function fetch() { var docRef = db.collection("Users").doc(uid); docRef.get().then(function (doc) { console.log(doc.data); }).catch(function (error) { console.log("Error getting document:", error); }); }});我如何存儲uid以便以后檢索它以進行數據庫操作。當前,運行該check函數將返回uid未定義的錯誤。如果我嘗試登錄uid控制臺也一樣。我猜該函數在偵聽器解析之前運行,但是我將如何解決此問題。由于用戶之間的互聯網連接速度不同,設置計時器也無濟于事(添加代碼)check1();check3();//fetch();function check1() { if (typeof uid === 'undefined') { console.log("not ready"); return false }}function check3() { if (check1 == false) { check1(); } else { console.log("ready"); //here this logs ready console.log(typeof uid); //then here it logs "undefined" still fetch(); //so this function call brings the error }}function fetch() { var docRef = db.collection("Users").doc(uid); docRef.get().then(function (doc) { console.log(doc.data(); }).catch(function (error) { console.log("Error getting document:", error); });}check3如果uid未定義,為什么函數準備好記錄日志。我還需要隱藏特定的鏈接,直到uid具有值為止。我該如何改善上述代碼而無法隱藏鏈接
將回調附加到onauthStateChanged偵聽器firebase
冉冉說
2021-04-06 17:14:34