1

This post helps me understand the reason why but it's a little brief on the solution.

The documentation mentions the callback functions .done(), .fail() and .always() but I've tried .done() and couldn't get my variable outside the call.

Here is my relevant code:

var countries = [];

$.getJSON("js/flags.json", function(data) {
    $(data.flags).each(function(i) {
        countries.push(data.flags[i]);
    });
    console.log(countries);    // returns a big ol array :)
});
console.log(countries);    // returns an empty array :(

I just want to be able to use this array globally. What am I missing?

Community
  • 1
  • 1
wetjosh
  • 6,288
  • 4
  • 23
  • 32
  • 1
    The problem is *timing*, not global availability of a variable. The last line runs long before `countries` is populated. That's why you need to run all your logic inside of the callback functions. – mellamokb Apr 14 '14 at 23:49
  • Yeah, I noticed that the console logs those in reverse (cause the last is executed before the first finishes. So that's the solution? Just run everything inside? – wetjosh Apr 14 '14 at 23:50
  • 1
    Unfortunately, yes. Event-based programming is sensitive to [callback hell](http://callbackhell.com/). You can avoid it somewhat by linking together dependencies with [promises](https://api.jquery.com/promise/). – mellamokb Apr 14 '14 at 23:53
  • @mellamokb: OP already uses jquery (and for them A+ may be not required yet) – zerkms Apr 14 '14 at 23:54
  • @zerkms: Good point, updated my comment. – mellamokb Apr 14 '14 at 23:54

1 Answers1

0

What u/Adi mentioned in this post is that in an Ajax call, the a meaning asynchronous, when you try to console log the countries array the Ajax call is not done yet and so the array is empty.

What I would do is wrap the Ajax call in a function and pass a callback to that function:

function someCallBackFunction(arr){
   console.log(arr)
}

function yourFunction(someCallBackFunction){
  $.getJSON("js/flags.json", function(data) {

    $(data.flags).each(function(i) {
        countries.push(data.flags[i]);
    });
    console.log(countries);

    someCallbackFunction(countries)
  });
}
Spencer
  • 47
  • 4
  • Is there a way to access the data in my JSON file NOT asyc? – wetjosh Apr 15 '14 at 00:33
  • If you don't want to make an Ajax call check out this [post](https://stackoverflow.com/questions/12995560/how-to-locally-fetch-json-without-ajax). Otherwise if you stick with Ajax there is no way, I know of, to make a non async call. – Spencer Apr 15 '14 at 00:41
  • 1
    I found a way here: http://stackoverflow.com/questions/2765411/is-it-possible-to-set-asyncfalse-to-getjson-call – wetjosh Apr 15 '14 at 00:45