In my HTML I have several buttons. A button appends an object to a json file named game.json. This file contains an array with objects. After appending a new object to an array I would like to get the length of the array.
For example:
game.json contains an array with 3 objects. After clicking a button, another object is appended to the array (which now contains 4 objects). Then I would like to return the length of the array (4). However, it returns the length before the new object is appended. I understand this is because of Javascript being asynchronous.
I tried to prevent this using the following code:
let mydata;
function checkData() {
$.ajax({
url: 'db/game.json',
async: false,
dataType: 'json',
success: function(json) {
mydata = json;
}});
console.log(mydata.length)
}
However, considering the example above, this still logs 3 instead of 4.
Is there any way to prevent the log (or even better, a return) from happening when the json is not yet fully loaded?