2

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?

Thijmen
  • 307
  • 1
  • 9
  • 4
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Luca Kiebel Jun 04 '18 at 19:47
  • You don't append to but overwrite the array. – str Jun 04 '18 at 19:51
  • Sorry, you are right indeed. Do you have suggestions on how to solve my problem? – Thijmen Jun 04 '18 at 19:53
  • Yes, have a look at the duplicate question. – str Jun 04 '18 at 19:54
  • I seem to have figured it out using the duplicate question. However, now I have another problem: I can't seem to figure out how to return a variable from an ajax call. – Thijmen Jun 04 '18 at 20:23
  • Well if the problem really is that you are overwriting instead of appending, the problem is the equal sign. push() to your array or concat() them. – Drumline18 Jun 04 '18 at 21:10

0 Answers0