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.