【问题标题】:What is the best way to use async/await inside onAuthStateChanged() of Firebase?在 Firebase 的 onAuthStateChanged() 中使用 async/await 的最佳方法是什么?
【发布时间】:2019-06-13 14:50:36
【问题描述】:

我在 React Native 中使用 Firebase 身份验证和异步/等待。我正在寻找一种更好的方法来等待内部 firebase 功能。所以我的问题是在firebase.auth().onAuthStateChanged() 中使用 async/await 的最佳方式是什么?

现在,我以这种方式实现它。在onAuthStateChanged() 中创建一个异步函数并调用它自己。就像下面的例子......但是,我觉得它看起来很奇怪。

firebase.auth().onAuthStateChanged(user => {
  const asyncFunc = async () => {
    await doSomething();
  }

  asyncFunc();
});

有没有更好的实现方式?

感谢您的回答。

【问题讨论】:

    标签: javascript reactjs firebase async-await firebase-authentication


    【解决方案1】:
    firebase.auth().onAuthStateChanged(async user => {
      const data = await getData();
      const action = await doSomething();
      // etc.
    });
    
    
    // also you can use
    async function asyncHandler(user) {
        const data = await doSomething();
    }
    
    firebase.auth().onAuthStateChanged(asyncHandler);
    

    【讨论】:

    • 哦,为什么我想念那个。我曾经像您的第一个示例一样实现,但出现错误。所以我认为它不能以这种方式实现。也许我误解了什么。
    • 参加聚会有点晚了,但是有人知道如何使用颤振来做到这一点吗? Firebase.auth 返回用户后,似乎找不到调用 Firestore 的方法。
    • 嗨 dteterevkov。关于颤振,你可以这样做。 Stream get user { return _auth.onAuthStateChanged.asyncMap((FirebaseUser firebaseUser) => _yourAsyncMethod(firebaseUser));魔法就在 asyncMap 中 :-) 希望这会对你有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2015-04-10
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 2021-11-02
    • 2017-12-28
    • 2018-12-16
    相关资源
    最近更新 更多