0

I'm grabbing JSON from reddit's API, and placing the JSON objects into a global array.

var stories = [];

var request = new XMLHttpRequest();
request.open('GET', 'http://www.reddit.com/r/news/top.json?limit=5', true);

request.onload = function() {
    var rawStories = JSON.parse(request.response);
    for (var i in rawStories.data.children) {
        var story = {};
        story.title = rawStories.data.children[i].data.title;
        stories.push(story);
    }
};

alert(stories); //Here I am accessing stories in global scope.

The above global alert(stories) shows the empty initialized stories array. Moving the alert inside the function displays a properly filled array of objects.

How can I have a globally accessible stories array? My misunderstanding is either in the asynchronous nature of the request.onload function or I'm having scope trouble (or both).

agm
  • 153
  • 1
  • 5
  • As you mentioned, it's asynchronous - The _onload_ will invoke after the `alert` so at the time the `alert` is invoked, `stories` hasn't yet had any data _pushed_ to it – Paul S. Mar 28 '15 at 02:30
  • Have a look at the non-jquery answer to that duplicate question. – James Montagne Mar 28 '15 at 02:35
  • you could use synchronous, but note that this option is deprecated to avoid abuse of sync. like `request.open('GET', 'http://www.reddit.com/r/news/top.json?limit=5', false);` – super Mar 28 '15 at 02:56

0 Answers0