skip to Main Content

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?

2

Answers


  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
        }
    }
    
    Login or Signup to reply.
  2. You are missing the return statement before your checkPermission() and requestPermission()call

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search