currentUserSync后的调用函数 - 异步等待问题
问题描述:
我正在使用react-native-google-signin。我的代码是:currentUserSync后的调用函数 - 异步等待问题
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
}
随着.then(this._someFunction(user));
,我想将user
传递给函数_someFunction
。
错误是Play services error undefined Cannot read property 'id' of undefined
。
我想要在GoogleSignin.currentUserAsync()
完成时调用设置user
的函数。我究竟做错了什么?
答
async..await
与正常承诺代码混合在一起,而不是一个好方法。
.then(this._someFunction(user))
无效,因为then
需要一个函数作为参数,并且它收到undefined
。此外,user
在此处未定义。
应该
const user = await GoogleSignin.currentUserAsync();
this._someFunction(user);
这正是async..await
是。这是可行的,以平整功能并避免then
。