【问题标题】:Wait for firebase.auth initialization before reading another function在读取另一个函数之前等待 firebase.auth 初始化
【发布时间】:2020-01-06 12:23:26
【问题描述】:

我对 firebase 和 javascript 非常陌生。

我的项目:构建一个私人消息应用程序。为此,我想在 firestore 中定义一个子集合,用于使用当前用户 ID 和目标用户 ID 进行私人消息传递。

这是允许这样做的函数:

// generate the right SubCollection depending on current User and the User he tries to reach
function dmCollection(toUid) {

  if (toUid === null) {
    // If no destination user is definer, we set it to the below value
    toUid = 'fixed_value';
  };
  const idPair = [firebase.auth().currentUser.uid, toUid].join('_').sort();
  return firebase.firestore().collection('dms').doc(idPair).collection('messages');
};

我的问题:我想使用firebase.auth().currentUser.uid 属性,但看起来函数没有等待firebase.auth 初始化。我该如何解决这个问题?

其他信息: 我有两个函数调用第一个函数 (dmCollection):


// retrieve DMs
function messagesWith(uid) {
  return dmCollection(uid).orderBy('sent', 'desc').get();
};


// send a DM
function sendDM(toUid, messageText) {
  return dmCollection(toUid).add({
    from: firebase.auth().currentUser.uid,
    text: messageText,
    sent: firebase.firestore.FieldValue.serverTimestamp(),
  });
};

【问题讨论】:

  • 你可以使用异步等待!!

标签: javascript firebase google-cloud-firestore


【解决方案1】:

如果我正确理解了您的问题(“函数似乎没有等待firebase.auth 初始化”),您有两种可能的解决方案:

解决方案 1:在 Auth 对象上设置观察者

documentation 中所述,您可以使用onAuthStateChanged() 方法在Auth 对象上设置观察者:

通过使用观察者,您可以确保 Auth 对象不在 中间状态——比如初始化——当你得到当前的 用户。

所以你会修改你的代码如下:

// retrieve DMs
function messagesWith(uid) {
  return dmCollection(uid).orderBy('sent', 'desc').get();
};


// send a DM
function sendDM(toUid, messageText) {
  return dmCollection(toUid).add({
    from: firebase.auth().currentUser.uid,
    text: messageText,
    sent: firebase.firestore.FieldValue.serverTimestamp(),
  });
};

// generate the right SubCollection depending on current User and the User he tries to reach
function dmCollection(toUid) {

  if (toUid === null) {
    // If no destination user is definer, we set it to the below value
    toUid = 'fixed_value';
  };
  const idPair = [firebase.auth().currentUser.uid, toUid].join('_').sort();
  return firebase.firestore().collection('dms').doc(idPair).collection('messages');
};


firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    var messageText = '....';
    sendDM(user.uid, messageText)
  } else {
    // No user is signed in.
  }
});

解决方案 2:使用 currentUser 属性

您还可以“使用currentUser 属性获取当前登录的用户”,如同一doc 中所述。 “如果用户未登录,currentUser 为空”。

在这种情况下,你会这样做:

var user = firebase.auth().currentUser;

if (user) {
  var messageText = '....';
  sendDM(user.uid, messageText);
} else {
  // No user is signed in.
  // Ask the user to sign in, e.g. redirect to a sign in page
}

选择哪种解决方案?

这取决于您希望如何根据用户 uid 调用函数。

  • 如果您想在用户登录后立即调用函数,请使用解决方案 1。
  • 如果您想在另一个特定时刻(例如,在用户操作之后)调用函数,请使用解决方案 2。

【讨论】:

    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多