Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expo FileSystem.readAsStringAsync doesn't await

I'm trying to read a list of hospitals from a file in a React Native project using Expo FileSystem. I want to wait for the list to return so that I can render it on the screen. I can easily get the result in the ".then" block, but I'm struggling to figure out how to wait for the list from readAsStringAsync in the same function. My attempts always return the Promise and not the list, or an "unhandled promise rejection" error occurs. Here is my code:

getHospitals = async () => {
        let result = null;
        let content = await FileSystem.readAsStringAsync(FileSystem.documentDirectory + 'hospitals.json').then(function (data) {
            result = data;
        }).catch(function(error) {
                console.log(error);
            });
        return result;
    }

How can I wait for a result from readAsStringAsync?

like image 463
Goodmedalist Avatar asked Dec 02 '25 06:12

Goodmedalist


1 Answers

async, await is replacement for then, catch callbacks. They are not supposed to be used together.

getHospitals = async () => {
    let result = null;
    try {
        result = await FileSystem.readAsStringAsync(FileSystem.documentDirectory + 'hospitals.json');
    } catch(e) {
        console.log(e);
    }
    return result;
}
like image 149
AvcS Avatar answered Dec 03 '25 18:12

AvcS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!