currentUserSync之后的调用函数 - 异步等待问题

时间:2017-10-05 17:35:10

标签: javascript react-native ecmascript-6 async-await google-signin

我正在使用react-native-google-signin。我的代码是:

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

我希望能够在user完成时调用设置GoogleSignin.currentUserAsync()的函数。我做错了什么?

1 个答案:

答案 0 :(得分:2)

.then(this._someFunction(user))与常规的承诺代码混合在一起,但并不是很好。

then无效,因为undefined期望函数作为参数,并且它会收到user。此外,此时尚未定义const user = await GoogleSignin.currentUserAsync(); this._someFunction(user);

应该是

async..await

这正是then的用途。在实际可行的情况下,将函数展平并避免使用{{1}}。