使用async/await获取firebase.auth().currentUser [英] Get firebase.auth().currentUser with async/await

查看:129
本文介绍了使用async/await获取firebase.auth().currentUser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I successfully check user's authentication state with onAuthStateChange observer and redirect user to the Dashboard page (react-native project). However, on the dashboard I already want to show some user specific data, e.g. enrolled programs/statistics. For that I need currentUser object to be initialised and populated, which takes some time (I need uid from there to get some data from Database). Thus, i'm looking for some way to wait until this process finishes successfully. What I'm trying to do it to use async/await syntax in componentDidMount, but the result returned is null. (Same syntax successfully works in other screens, but fails in the first one)

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

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

What could be the best way to wait for currentUser object being loaded using async/await syntax? I believe that the reason could be that firebase returns null as the first result and then correct uid as the second one.

就目前的解决方法而言,我正在使用简单的setInterval函数,但是我不想增加那么多的加载时间.

For now for the workaround, I'm using simple setInterval function, but I do not want to increase amount of loading time that much.

  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);

推荐答案

setInterval的等效项是: //调用异步函数 waitForCurrentUser(function(uid){ 如果(uid) console.log('用户ID为',uid) })

The equivalence of setInterval is : //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
  };

干杯:)

这篇关于使用async/await获取firebase.auth().currentUser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆