0

So I've got some code that retrieves a series of objects from an API. When I try to store them in a global variable, it doesn't seem to do anything. Here's the code:

var current_corpus = {};

function page_init() { 
  $.getJSON("http://resource1.com", function(data) {
    populate_collections(data);
    populate_citations(data);
  });
}

function populate_collections(collections) {
  $.each(collections, function (i, item) {
    current_corpus[item] = [];
  });
}

function populate_citations(collections) { 
  $.each(collections, function (index, collection) {
    $.getJSON("http://resource2.com/" +   collection.collection_id, function(data) {
      current_corpus[collection] = data;
      console.log(current_corpus);
    });
  });
}

When this finishes, current_corpus is completely empty. Logging these items verifies that they're being returned from the resources I'm posting to. I think there's just something about the asynchronous nature of these calls that I'm missing.

The line

current_corpus[item] = [];

is superfluous I think as the line

current_corpus[collection] = data;

should do the same thing while also tying data to the key object. Either way at the end of these functions running trying to access current_corpus via the console just gives me back an empty object.

Resources for dealing with AJAX stuff like this would be appreciated as well.

Etheryte
  • 24,589
  • 11
  • 71
  • 116
pjc
  • 127
  • 1
  • 11
  • 2
    One word: "asynchronous". You need to read this: http://stackoverflow.com/a/14220323/816620 – jfriend00 Jun 09 '14 at 19:13
  • *"Either way at the end of these functions running trying to access current_corpus via the console just gives me back an empty object."* Because the "end of the function" is not the same as the end of the request. Simply access the object after the success callback is executed and everything is fine. – Felix Kling Jun 09 '14 at 19:26
  • Do you really need `populate_collections()`? – PeterKA Jun 09 '14 at 19:29
  • @user3558931 Yeah, I stripped out some stuff that does HTML formatting with the data that's already working to make it more readable. – pjc Jun 09 '14 at 20:07

1 Answers1

1

It all depends on what you want to do when the ajax requests complete. The A in ajax stands for Asynchronous meaning that such requests are non-blocking -- i.e. they will run in the background as control moves to the next line. Which explains why you're seeing an empty object right after the functions that invoke the ajax requests.

You can confirm that your code is working fine or you can do something once all the requests complete by using the following code snippet:

$(function() {
    $(document).on('ajaxStop', function() {
        console.log( current_corpus );
        //do something with the now fully constructed object
    });
});
PeterKA
  • 24,158
  • 5
  • 26
  • 48