1

Here's my problem

I have a JSON file full of country codes, and a function that gets a random country code, like this:

function getRandomCountryCode(specificMap){
  $.getJSON('../maps/' + specificMap + '.json', function( data ) {
    var countries = [];
    for (var i in data.country) {
      countries.push(data.country[i].code);
    }
    var rndCountryCode = countries[Math.floor(Math.random()*countries.length)];
    return rndCountryCode;
  });
};

In another function, I call the above function and try to store the rndCountryCode variable into another variable so it's available inside the new function.

function loadMap(map){
  var specificMap = map;
  var y = getRandomCountryCode(specificMap);
  console.log("Y is : " + y);
}

All I get is undefined. I did a lot of research (here and here and especially here) and realized this is because of asynchronous nature of $.getJSON, and that I should use callbacks but for the life of me I can't figure it out.

Thanks for all your help.

Community
  • 1
  • 1
codeWolf
  • 165
  • 3
  • 14

1 Answers1

1

Put the code you were going to do after

var y = getRandomCountryCode(specificMap);

in the success callback

function getRandomCountryCode(specificMap){
  $.getJSON('../maps/' + specificMap + '.json', function( data ) {
    var countries = [];
    for (var i in data.country) {
      countries.push(data.country[i].code);
    }
    var rndCountryCode = countries[Math.floor(Math.random()*countries.length)];
    >>>console.log("rndCountryCode  is : " + rndCountryCode );
    return rndCountryCode;
  });
};

Since getJSON is asynchronous and you dont know when the response will get back, the only way to guarantee that your code manipulating the response will work is putting it in the success handler(the second parameter to getJSON).

The success handler is exucuted when there has been a successful response regardless of how long it took.

AmmarCSE
  • 30,079
  • 5
  • 45
  • 53