1

What is the best way to just grab the content of a .json and store it to a var ? I've seen some threads but i just can't manage on my code...

function retrieve_json() {
  var content;
  $.when(
    $.getJSON("http://localhost/browsergame/data/test.json", function(data) {
      content = data;
    })
  ).then(function () {
    console.log(content);
    return content;
  });
}

var json_content = retrieve_json();
console.log (json_content);

the console.log within the function displays the correct content of the json, the console.log at the very end of my code shows 'undefined'. I guess the async is the main issue here. I have tried doing it with $.ajax but couldn't manage either. So, what is the best way to just grab the content of a .json file and store it to a var ?

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
ivsterr
  • 128
  • 1
  • 7

2 Answers2

1

The problem is that retrieve_json wont stop and wait until the json arrives from the server. The execution continues with whatever is after the statement starting with your $.when. In this case it's the end of the function. Since there is no return statement here, the function returns with the value 'undefined', what you store in json_content.

If you want to stop execution until the answer returns you have to wrap the next steps into a function and for example call it in the 'then' method of your example or just pass it to the getJSON where you store it in the content variable now.

And make sure you read up on how promises work.

Csene
  • 69
  • 4
0

Once code is async, it can't be made synchronous. You can only reliably use the content of your JSON in functions that you pass to promises or as callbacks, otherwise you have no guarantee that your JSON has been fetched when your code gets executed.

If you find even the promises syntax horrible you might be interested in async/await, a proposed syntax for ES7 that can be transpiled to ES5 right now with Babel.

Here's a good article which demonstrates the different approaches to asynchronous programming in JavaScript: The long road to Async/Await in JavaScript.

Community
  • 1
  • 1
lleaff
  • 4,249
  • 17
  • 23