0

I'm sure this is simple but I'm not really a JS developer.

I've got the following function that sets two arrays equal to a json response so that I can load the arrays into Chart.js

$(document).on("turbolinks:load",function(){
    var months = [];
    var values = [];

    $.getJSON({url: "/reports/graph_data.json", success: function(data){

        for (var i = 0, len = data.length; i < len; i++) {
            months.push(data[i][0]);
            values.push(data[i][1]);
        }
        alert(months); //DISPLAYS CORRECT MONTHS
    }});

    alert(months); //DISPLAYS NOTHING
});

Notice that I have two alerts in the code. The first alert displays the months from the response as I would expect but the second alert is empty. Why is this? I would've thought the scope wouldn't be broken when I referenced the array outside of the getJSON function.

Thanks in advance.

Cannon Moyer
  • 3,014
  • 3
  • 31
  • 75
  • 2
    It doesn't break the scope. The problem is with the timing. Which you can actually clearly see since the alert with the empty array shows up first. That tells you that the second `alert` in your code is called before the first one, i.e. before the `success` callback was called and data was added to `months`. – Felix Kling Apr 27 '18 at 22:33
  • Make sense. For some reason I thought this was a synch call which explains what was happening now. I appreciate your help. @FelixKling – Cannon Moyer Apr 27 '18 at 22:37

0 Answers0