0

I created a script which should fetch some Json data from an API endpoint and do some stuff with it. Here is what i tried:

var dataset

$.getJSON('http://127.0.0.1:8000/tst/l', function(data) {
  dataset = data

})

console.log(dataset) // Returns undefined

The problem with my code is that, right now, i can only use data inside the scope of the $.getJSON function, while i want that data to be stored on a global variable, which is dataset, so that i can use that data on another function. How can i do that? Should i do a loop and push the data from data into dataset or is there a simpler way?

Here is what my data looks like:

"results": [
      { "item": "First",  "id": "1847" .. },
      { "item": "Second", "id": "4442" ..},
      { "item": "Third",  "id": "3847" ..},
      //more records here 
    ]
Jack022
  • 867
  • 6
  • 30
  • 91
  • No matter how you do it, the data will only be available in the callback function, because the function is asynchronous. – Barmar Feb 21 '20 at 20:35
  • You are assigning the data to `dataset` correctly, but your `console.log` is running before the data is returned. – Ben Aston Feb 21 '20 at 21:07

0 Answers0