亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將變量分配給 firestore 值檢查

將變量分配給 firestore 值檢查

汪汪一只貓 2023-04-14 17:15:20
我正在嘗試分配bm_array給我的 firestore 數組(如果存在,則為空數組)。邏輯是檢查名稱為當前用戶 firebase uid 的 firestore 文檔。我能夠 console.log 我的預期數組(第 12 行),但是在實際數組分配給之前bm_array返回(第 25 行) 。我嘗試使用異步,但 bm_array 要么返回一個 promise 對象,要么返回 null。我不確定如何使用異步。nullbm_arrayvar bm_array = null;const getBookmarks = async() => {  var firestore = firebase.firestore();  var userBookmarks = firestore.collection("userBookmarks");  await firebase.auth().onAuthStateChanged(async function(user) {    if (user) {      // User is signed in.      var user = firebase.auth().currentUser;      await userBookmarks.doc(user.uid).get().then(async function(doc){        if (doc.exists){          bm_array = await doc.data().countries;          console.log(bm_array);        }else{          bm_array = [];        }      }).catch(function(error) {        console.log("Error getting document:", error);      });    } else {      return []    }  }); } getBookmarks(); console.log(bm_array);
查看完整描述

1 回答

?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

onAuthStateChanged()“添加觀察者以更改用戶的登錄狀態”。因此它會不斷觀察用戶的登錄狀態是否發生變化。

既然你想通過調用一個函數來執行你的業務邏輯,你最好使用屬性currentUser來獲取用戶值。

以下幾行應該可以解決問題:

?const getBookmarks = async () => {

? ? var firestore = firebase.firestore();

? ? var userBookmarks = firestore.collection('userBookmarks');

? ??

? ? const user = firebase.auth().currentUser;

? ??

? ? if (user) {

? ? ? ? const docSnapshot = await userBookmarks

? ? ? ? ? .doc(user.uid)

? ? ? ? ? .get();

? ? ? ? ? // Note that you need to use await only in the above line, since it is the only asynchronous operation in your async function? ? ? ? ? ? ??


? ? ? ? ? if (docSnapshot.exists) {

? ? ? ? ? ? ? bm_array = docSnapshot.data().countries;

? ? ? ? ? } else {

? ? ? ? ? ? ? bm_array = [];

? ? ? ? ? }

? ? ? } else {

? ? ? ? ? // Not sure you should return anything here,

? ? ? ? ? // since you just call the function as getBookmarks(); without using the potential returned value

? ? ? ? ? // Note that you don't return anything when user is not undefined, i.e. in the first part of the if block, above

? ? ? ? return [];

? ? ? }

? ??

? };


查看完整回答
反對 回復 2023-04-14
  • 1 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號