Async/Await with Fetch Js [Duplicate]

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);
3

async function can be called in two ways.

  1. using then method
request.then(resp => console.log(resp)).catch(e => console.log(e));
  1. using await - to use await you need a async function otherwise await keyword will give error and can only be called inside a async function.
async function exe() {
 try {
  const result = await request(); // Now this will wait till it finished
  console.log(result);
 } catch(e) {
  console.log(e);
 }
}
1

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

5

fetch(url).then(response => response.json()).then(data => console.log(data))

1
Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest