I am trying to create an array in my JavaScript object that contains objects pulled in from a JSON file using the $.getJSON() function in jQuery. I am running into scope issues where it seems like the array elements are getting set inside the $.getJSON() function, but outside of it the array is empty. Here is the code:
function player(playlist){
...
var tracks = [];
this.start = function() {
...
$.getJSON(playlist, function(data){
$.each(data.tracks, function(key,value){
var track_info = function(info){return info}(value);
tracks.push(track_info);
});
console.log("from .getJSON function");
console.log(tracks);
});
console.log("outside .getJSON function");
console.log(tracks);
...
};
...
$(document).ready(function(){
var the_player = new player(playlist);
the_player.start();
)};
The output is:
outside .getJSON function
[]
from .getJSON function
[Object, Object, Object]
And all the objects contain the correct data from the JSON file.
I’m perplexed about this issue, can someone help me understand it?
The hint is the order:
Followed by
Your outer code is executing before you’ve got a JSON response, so not surprisingly,
tracksis empty. This may seem counter-intuitive –from .getJSON functionappears in the source first, yet is executing second! This is because.getJSONis not synchronous. It doesn’t execute its callback argument before continuing to the next statement. It immediately continues to the next statement, and executes the callback later.