gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:20:51 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

干杯 :)

关于javascript - 使用 async/await 获取 firebase.auth().currentUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43821921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com