简体   繁体   中英

Call function after currentUserSync - Async Await issue

I'm using 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)); , I want to pass the user to the function _someFunction .

The error is 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. What am I doing wrong?

async..await is mixed with regular promise code, and not in a good way.

.then(this._someFunction(user)) is invalid, because then expects a function as an argument, and it receives undefined . Also, user is not defined at this point.

It should be

const user = await GoogleSignin.currentUserAsync();
this._someFunction(user);

This is exactly what async..await is for. To flatten the function and avoid then s when this is practical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM