0

I'm trying to populate an array in JavaScript using an anonymous function in the jQuery getJSON() function as follows.

$(document).ready(function() {

    function Link(url, title) {
        this.url = url;
        this.title = title;
    }
    var links = [];

    $.getJSON("http://reddit.com/r/programming/.json?jsonp=?", function(data) {
        $.each(data.data.children, function(i, item) {
            var title = item.data.title;
            var url = item.data.url;

            links.push(new Link(url, title));
        })
    });

    for(var i=0; i< links.length; i++) {
        var output = "<a href='" + k + "'>" + links[k] + "</a>";
        $('<p>' + link + '</p>').appendTo('#content');
    }

});

But, when I hit the for loop, the links array shows up empty. What's going on here?

hodgesmr
  • 2,765
  • 7
  • 30
  • 41

3 Answers3

3

Try that :

    $(document).ready(function() {

        function Link(url, title) {
            this.url = url;
            this.title = title;
        }

        $.getJSON("http://reddit.com/r/programming/.json?jsonp=?", function(data) {
            var links = [];
            $.each(data.data.children, function(i, item) {
                var title = item.data.title;
                var url = item.data.url;

                links.push(new Link(url, title));
            })
            for(var i=0; i< links.length; i++) {
                var output = "<a href='" + k + "'>" + links[k] + "</a>";
                $('<p>' + link + '</p>').appendTo('#content');
            }
        });


    });

Your loop was probably executed before your callback ;)

tibo
  • 5,326
  • 4
  • 37
  • 53
  • "Probably" - With an async call the loop would _definitely_ be executed before the callback. – nnnnnn Jun 05 '12 at 03:39
  • It is an asynchronous call, so nothing is guaranteed in theory. But I agree, on the practice, it will be always executed after . – tibo Jun 05 '12 at 03:43
  • Thank you for this. Is there a way to implement this such that execution blocks until all of the json data has been pulled? I'd like to be able to pull from many json sources and populate arrays of data (this was just my first example) and then do work on the various filled arrays. – hodgesmr Jun 05 '12 at 03:43
  • (Not to start an argument, but) I'm not aware of any browsers that run JS on more than one thread. This means any currently executing code will _always_ complete before any async callbacks. – nnnnnn Jun 05 '12 at 03:47
3

That's because $.getJSON is an asynchronous method. The code execution continues even after $.getJSON and reaches the for loop, by which time, your async request hasn't completed yet. You should move the loop within $.getJSON.

Sang Suantak
  • 5,213
  • 1
  • 27
  • 46
1

This jsFiddle http://jsfiddle.net/cArYg/2/ shows the iteration occuring before the getJson callback

jflood.net
  • 2,446
  • 2
  • 21
  • 19