Search code examples
javascriptasync-awaitfetch

async/await with fetch JS


I have a problem with creating a function that will stop all the code until it finishes. I thought making async/await. In that function I should make fetch, but it says promise {}, when I return the result code:

const request = async (url) => {
    const response = await fetch(url);
    const json = await JSON.stringify(response.json());
    return json;
}
let tree = request('humans.json');

console.log(tree);


Solution

  • When you add async prior to the function then this means that the function will return a promise in response, and in order to work with that result You need to do something like this

    tree.then(()=>{
    //Promise Successful, Do something
    }).catch(()=>{
    //Promise Failed, Do something
    })
    

    If you want to use fetch, you can do something like this

    fetch('humans.json')
      .then(response => response.json())
      .then(data => console.log(data)).catch(()=>{
       ///Exception occured do something
    })
    

    The above fetch statement will log the json data into console from humans.json for more info on how fetch api works, you can refer to MDN here