async/await with fetch JS

26,069

Solution 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

Solution 2

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

Solution 3

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

Share:
26,069

Related videos on Youtube

Admin
Author by

Admin

Updated on June 16, 2021

Comments

  • Admin
    Admin about 3 years

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

    • Barmar
      Barmar about 3 years
      Declaring a function async makes it return a promise automatically.
    • Muhammad Saquib Shaikh
      Muhammad Saquib Shaikh about 3 years
      You are calling async function request() prefix await against it otherwise it will not work. let tree=await request('human.json'); make sure it is wrapped inside async function or you can chain .then() to resolve the promise
    • RaisinBranCrunch
      RaisinBranCrunch over 2 years
      The trick is that you also have to await the response.json(). It's really not the same as the "duplicate" answers because of that.
  • amitchauh4n
    amitchauh4n about 3 years
    try catch is use to handle error if you need, just like we catch error in catch() method in after then().
  • deepakchethan
    deepakchethan about 3 years
    How does this stop the execution of function?
  • Admin
    Admin about 3 years
    I know that I can use fetch like that, but I need it in a function so it will return the object
  • Uzair Saiyed
    Uzair Saiyed about 3 years
    just like you I was stuck on the same thing a few months back, and honestly, fetch doesn't work that way you could try returning the data but you will see that the promise isn't fulfilled, same goes for async/await too because it executes independently of rest of the code block and so you can't return any data. You can see 1000s of examples but you wont come across one that returns some data from inside of fetch or async function, because its not possible
  • Admin
    Admin about 3 years
    amitchauh4n gave example. Isn't it's working?
  • Uzair Saiyed
    Uzair Saiyed about 3 years
    mine is working too, all I am saying is that you can't return data from inside of fetch or async block, like you want, that data is accessible only within the scope of fetch
  • Admin
    Admin about 3 years
    async function loadDevs() { const response = await fetch('humans.json'); const devs = await response.json(); return devs; } document.addEventListener("DOMContentLoaded", async () => { try { tree = await loadDevs(); } catch(e) { console.error(e); } })