javascriptasynchronousfetch

How to pull data out of Async Fetch function


This seems like it should be very simple and basic, but I'm unable to get data out of an Async fetch function. Below is my code. Any insight into what I might be doing wrong is much appreciated.

const getData = async(url)=>{
    try{
      const response = await fetch(url);
      const data = await response.json();
      console.log(data) //<-- this is working
      return data;
    }
    catch (error){
      console.log(error);
    }
}

const desiredData = getData(url);
console.log(desiredData) // <--this is empty

Solution

  • Calling an asynchronous function returns a Promise object. You can try to do this:

    const desiredData = getData(url);
    desiredData.then((value) => console.log(value))
    

    Also you can check this link