0

I have a problem with my API call. When I return my data I get a empty array with data. This is my code from call the API.

function HeadQuartersGet() {
   var data = [];
   async function fetchData() {
      var myHeaders = new Headers();
      myHeaders.append("Content-Type", "application/json");
      var requestOptions = {
         method: 'GET',
         headers: myHeaders,
         redirect: 'follow'
      };
      var json = await fetch(url, requestOptions)
         .then((response) => {
            return response.json();
         })
         .then((result) => {
            console.log(result);
         });
      data = JSON.stringify(json);
   }
   fetchData();
   console.log(data);
   return [data];
};

My data log is empty. What I need to do to get data from the result because result log has my data.

palaѕн
  • 72,112
  • 17
  • 116
  • 136
Ionut
  • 47
  • 7
  • Your data will be empty because of asynchronous behavior of JavaScript. The problem is, there's a little confusion with how you are using async/await. No need to use promises (`.then(), .catch()`) when `async/await` is present. Your response data will be assigned to json variable that you've created. – tipos Mar 07 '20 at 08:55

1 Answers1

0

Inside your fetchData function, return a json Promise since this is what the first execution of fetch returns, after calling fetchData inside HeadQuartersGet evaluate your promise to the actual data and console.log it

 async function HeadQuartersGet() {
  let data = [];
  async function fetchData() {
    const myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    const requestOptions = {
      method: 'GET',
      headers: myHeaders,
      redirect: 'follow'
    };
    return await fetch(url, requestOptions);

  }
  data = await fetchData();
  console.log(data);
  return [data];
};
EugenSunic
  • 13,162
  • 13
  • 64
  • 86