0
votes

I have 2 function calls:

const result = _checkPermissions();
if (result === 'granted') {
    this._googleSignIn();
} 

I want _checkPermissions() to return before I run the if statement.....however I cant seem to do this and code just continues on to if statement before _checkPermissions() has returned.

I know its got something to do with async await but i cant figure it out

Below is code for _checkPermissions()

export const _checkPermissions = async () => {
  const result = await check(
    Platform.select({
      android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
      ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
    }),
  );
  switch (result) {
    case 'blocked':
      return 'blocked';
    case 'granted':
      return 'granted';
3

3 Answers

4
votes

You just need to await _checkPermissions. Since _checkPermissions is an async function it returns a promise which resolves/rejects at a later point of time. You can use await with the promise or you can write inside the .then block of promise.

Promise approach:

const result = await _checkPermissions();
if (result === 'granted') {
    this._googleSignIn();
} 
  • If you are using await you need to add async to the parent function.*

.then approach:

_checkPermissions().then(result => {
    if (result === 'granted') {
        this._googleSignIn();
    } 
})
3
votes

You still need to put await in front of _checkPermissions();

const result = await _checkPermissions();
if (result === 'granted') {
    this._googleSignIn();
} 
0
votes

although adding await is the perfect option , but in case you dont get the required result then you can use setInterval under if result == 'granted'

if (result === 'granted') {
    setInterval(() => {
       this._googleSignIn();
    },2000)
} 

your this._googleSignIn(); will run after 2 seconds till then your promise will be resolved .... this is just a trick better answer is to use await .