JS: How to make my code wait until this function has returned?

159 Views Asked by At

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

There are 2 best solutions below

0
On

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
    }
}
1
On

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