2

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?

2 Answers 2

4

The hint is the order:

outside .getJSON function
[]

Followed by

from .getJSON function
[Object, Object, Object]

Your outer code is executing before you've got a JSON response, so not surprisingly, tracks is empty. This may seem counter-intuitive - from .getJSON function appears in the source first, yet is executing second! This is because .getJSON is 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.

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

2 Comments

Ahh! That makes sense! So is there a good way to get .getJSON to finish before moving on in the code? Should I just call the next code from within the .getJSON call?
@DorkRawk: "Should I just call the next code from within the .getJSON call?" - Got it in one!
1

$.getJSON is an AJAX call, and is asyncrhonous. That means you console.log("outside .getJSON function"); gets called before your AJAX calls return (and populate the array). The hint that this is the what is happening is that your output you see 'outside' before 'inside'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.