Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

You shouldn't use then and catch when using async, await. The point of async await is to get rid of callbacks – AvcS May 31, 2018 at 17:53

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;
                Thanks, I'm understanding the syntax better and trying your corrections, but I still only get the Promise returned and not the result.
– Goodmedalist
                May 31, 2018 at 18:16
                I used this code and added new state-variable "hosps" and used "this.setState({ hosps: result })" in the try block, instead of returning the result. My component now returns a list.
– Goodmedalist
                May 31, 2018 at 19:49
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.