0

I have a $.getJSON() function set up like this.

var colNames = [];                 
$.getJSON(reqURL, function(data) {
 $.each(data.rows, function(key,val){
    var colName = val.column_name;
    colNames.push(colName);
 });
 console.log(colNames);
}));
console.log(colNames);

The console.log() outside the $.getJSON() function fires first, meaning colNames never gets filled.

What must I change so that colNames gets filled?

Username
  • 3,463
  • 11
  • 68
  • 111
  • It's asynchronous. The `console.log`s are called before the function that you pass into `$.each` is called. – Sumner Evans Jul 25 '17 at 22:52
  • Drop `console.log(colName)` just right after you declare it and tell us what does it return. – kind user Jul 25 '17 at 22:53
  • @Kinduser The first one returns `colnames` all filled up. The second one returns an empty array. – Username Jul 25 '17 at 22:54
  • @SumnerEvans has explained you why it happens this way. – kind user Jul 25 '17 at 22:55
  • I'm still not sure what to do after reading the other question – Username Jul 25 '17 at 23:01
  • Since the `getJSON` function is **asynchronous**, the `console.log` function at the end of your code executes before it was finished (loaded). That's why it returns an empty array. – kind user Jul 25 '17 at 23:03
  • But I do not understand what I need to change to make the second `console.log()` print a filled `colNames` – Username Jul 25 '17 at 23:05
  • Easiest but not really clever would be using timeout. `setTimeout(() => { console.log(colNames) }, 1000)`. – kind user Jul 25 '17 at 23:06
  • Is there a way to do this without `setTimeout()`? – Username Jul 25 '17 at 23:15
  • @Username What you need to do is to understand that the values will never be available until the callback you passed to `$.getJSON()` gets invoked and anything that is dependent on these values has to be deferred to that callback. In other words, there's nothing you can do to make the data available at the point of your second `console.log()`, that would require time travel. – Lennholm Jul 25 '17 at 23:23
  • @MikaelLennholm How would I set up the code to do that? – Username Jul 25 '17 at 23:26
  • 1
    @Username In a way you're already doing it. Your first `console.log()` is inside the callback function where the data is available. Anything you need to do with the data has to be done at that point. – Lennholm Jul 25 '17 at 23:29

0 Answers0