There is such a code.

var model = { getConfig: function(){ that = this; $.getJSON("latestProjects.json" , function(projects){ that.property = projects.length; }); alert("model.property = " + that.property); } } model.getConfig(); 

and the latestProjects.json file in the root folder

 {"length":6, "name": "Joe"} 

The thing is, I want to get the json object and write it into the model property (model.property) // I want model.property.length // = 6, etc. But for the reason I don’t understand, everything that happens inside the getJSON function is executed last, hence the result - the variable (property) remains undefined until the end of the script. If you register console.log (model.property) directly in the browser console (after executing the script), the result will be = 6;

How to solve this problem? I want to save an object from JSON into a variable in order to have access to it while the user is working with the browser page. (I don’t want every time I need to get data from a static json file, load it with the getJSON method, and it would be nice to separate data from operations on them). I would be glad to have good advice.

Reported as a duplicate by user207618, aleksandr barakin , cheops , tutankhamun , HamSter 19 Oct '16 at 6:35 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Same asynchronous request. No one will wait for a response, but the function will continue immediately. The solution is Promise . Soon and async/await . For details, see the duplicate proposed duplicate. - user207618

1 answer 1

I don't know js well but it should work

model.property = projects

  • this is just a simplified and less flexible assignment method. - IntensNow
  • nevertheless, in the context of this problem, in essence, this is the same and does not solve problems. - IntensNow