This question has already been answered:
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.
Promise. Soon andasync/await. For details, see the duplicate proposed duplicate. - user207618