0

Having a strange issue where im trying to parse some JSON for use with Chart.JS .. I can console log within the function and use the array so to say as expected but outside of that function even though i have made it a Global variable the array is empty after the function runs and i print it out to the console.

var data = {}
const api_url = "http://localhost:5000/"
var currentPage = window.location.href
currentPage = currentPage.split("/")

currentPage = api_url + currentPage[4]

console.log(currentPage)

async function getJson() {
  const response = await fetch(currentPage);
  data = await response.json();

  console.log(data)


}


getJson()

console.log(data)
  • It looks like it might be a scoping issue. Can you replace `getJson(); console.log(data);` with `console.log(getJson())` and add `return data` to the end of `getJson`? Then let me know if it's still broken. – Lewis Jun 13 '20 at 09:29
  • This is expected. It is how javascript works due to its async nature. The `console.log` at the end will be called before `getJson()` as `getJson` is an asynchronous method – Hemant Parashar Jun 13 '20 at 09:32

1 Answers1

1

Well, you are executing an async function but you don't await.

So, instead of this:

getJson()

Use this:

getJson().then(_ => console.log(data))
aprogrammer
  • 1,764
  • 1
  • 10
  • 20