-1

I have the following code in my React Native app for checking if permission is granted for a camera on Android:

function hasAndroidPermission() {
    checkPermission('camera')
        .then(res => {
            if (res === RESULTS.DENIED) {
                requestPermission('camera')
                    .then(res => {
                        if (res === RESULTS.DENIED) {
                            return false
                        } else {
                            return true
                        }
                    })
                    .catch(err => {
                        // console.log(err)
                    })
            } else {
                return true
            }
        })
        .catch(err => {
            // console.log(err)
        })
}

I want to execute some other code depending on the result of hasAndroidPermission(). I tried this (in an async function):

let androidPermission = await hasAndroidPermission()
if (androidPermission) ...

The code executes the if block before hasAndroidPermission() has returned. How can I make it wait?

gkeenley
  • 6,088
  • 8
  • 54
  • 129

2 Answers2

1

You should use async/await and make hasAndroidPermission an async function:

async function hasAndroidPermission() {
    const res = await checkPermission('camera')
    if (res === RESULTS.DENIED) {
        const res = await requestPermission('camera')
        if (res === RESULTS.DENIED) {
            return false
        } else {
            return true
        }
    } else {
        return true
    }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

You are missing the return statement before your checkPermission() and requestPermission()call

Manuel Duarte
  • 644
  • 4
  • 18