[英]Call function after currentUserSync - Async Await issue
I'm using react-native-google-signin .我正在使用react-native-google-signin 。 My code is:
我的代码是:
async _setupGoogleSignin() {
try {
await GoogleSignin.hasPlayServices({ autoResolve: true });
await GoogleSignin.configure({
webClientId: '<from web>',
offlineAccess: true
});
const user = await GoogleSignin.currentUserAsync()
.then(this._someFunction(user)); // Is this correct?
console.log(user); // this works. User is logged
}
catch(err) {
console.log("Play services error", err.code, err.message);
}
}
_someFunction(user){
console.log("ID: ",user.id) // Error is thrown here
this.setState({id: user.id}); // This is not set
}
With the .then(this._someFunction(user));
随着
.then(this._someFunction(user));
, I want to pass the user
to the function _someFunction
. ,我想将
user
传递给函数_someFunction
。
The error is Play services error undefined Cannot read property 'id' of undefined
.错误是
Play services error undefined Cannot read property 'id' of undefined
。
I want to be able to call the function that sets the user
when GoogleSignin.currentUserAsync()
is completed.我希望能够在
GoogleSignin.currentUserAsync()
完成时调用设置user
的函数。 What am I doing wrong?我究竟做错了什么?
async..await
is mixed with regular promise code, and not in a good way. async..await
与常规的async..await
代码混合在一起,而且不是很好。
.then(this._someFunction(user))
is invalid, because then
expects a function as an argument, and it receives undefined
. .then(this._someFunction(user))
无效,因为then
需要一个函数作为参数,并且它接收undefined
。 Also, user
is not defined at this point.此外,此时未定义
user
。
It should be它应该是
const user = await GoogleSignin.currentUserAsync();
this._someFunction(user);
This is exactly what async..await
is for.这正是
async..await
的用途。 To flatten the function and avoid then
s when this is practical.在可行的情况下,将函数展平并避免
then
s。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.