使用 async/await 获取 firebase.auth().currentUser

Den*_*nis 8 javascript firebase react-native firebase-realtime-database ecmascript-2017

我成功地使用 onAuthStateChange 观察者检查用户的身份验证状态并将用户重定向到仪表板页面(react-native 项目)。但是,在仪表板上我已经想显示一些用户特定的数据,例如注册的程序/统计信息。为此,我需要初始化和填充 currentUser 对象,这需要一些时间(我需要从那里获取 uid 从数据库中获取一些数据)。因此,我正在寻找某种方法来等待此过程成功完成。我正在尝试在 componentDidMount 中使用 async/await 语法,但返回的结果为 null。(相同的语法在其他屏幕中成功运行,但在第一个屏幕中失败)

async componentDidMount() {
  try {
    let uid = await firebase.auth().currentUser.uid;
    console.log(uid);
  } catch(error) {
    console.log(error);
  }
}
Run Code Online (Sandbox Code Playgroud)

等待使用 async/await 语法加载 currentUser 对象的最佳方法是什么?我相信原因可能是 firebase 返回 null 作为第一个结果,然后更正 uid 作为第二个结果。

对于现在的解决方法,我使用简单的 setInterval 函数,但我不想增加太多加载时间。

  let waitForCurrentUser = setInterval(() => {
    if ( firebase.auth().currentUser.uid !== null ) {
        clearInterval(waitForCurrentUser);
        let uid = firebase.auth().currentUser.uid;
        this.setState({uid});
        return firebase.auth().currentUser.uid;
    } else {
      console.log('Wait for it');
    }
  }, 700);
Run Code Online (Sandbox Code Playgroud)

Cod*_*ngh 0

setInterval 的等价物是:

//calling the asynchronous function
  waitForCurrentUser(function(uid){
   if(uid)
   console.log('the user id is',uid)
  })

   async waitForCurrentUser(userIdIs){

    try {
       let uid = await firebase.auth().currentUser.uid;
       if(uid)
       {
         clearInterval(waitForCurrentUser);        
         this.setState({uid});
         userIdIs(uid); 
       }
       else {
       console.log('Wait for it');
      }

    }

    catch(e){
     console.log(e)
    }

  //  return userIdIs(uid);//returns promise
  };
Run Code Online (Sandbox Code Playgroud)

干杯:)