12

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);
  • Declaring a function `async` makes it return a promise automatically. – Barmar Jun 13 '21 at 05:07
  • 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 – Muhammad Saquib Shaikh Jun 13 '21 at 05:35
  • 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. – RaisinBranCrunch Feb 22 '22 at 17:21

3 Answers3

7

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);
 }
}
Amit Chauhan
  • 1,810
  • 3
  • 17
  • 25
6

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

Uzair Saiyed
  • 575
  • 1
  • 6
  • 16
  • 1
    I know that I can use fetch like that, but I need it in a function so it will return the object –  Jun 13 '21 at 13:27
  • 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 – Uzair Saiyed Jun 13 '21 at 13:30
  • amitchauh4n gave example. Isn't it's working? –  Jun 13 '21 at 13:42
  • 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 – Uzair Saiyed Jun 13 '21 at 13:43
  • 1
    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); } }) –  Jun 13 '21 at 14:12
1

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

Mayur
  • 21
  • 1