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.

1
  • The answer below helped me understand callbacks now. Should I delete the question? Or leave it be? Commented Apr 26, 2015 at 11:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

can you explain what the issue and solution is in the answer ?
Thanks man, I managed to make it work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.