0
function getContent(type) {
  var content = [];
  $.get(`/${type}.json`, function(data) {
    $.each(data, function(index, hash) {
      content.push(hash);
    });
    // 1. content = [object, object, etc..]
  });
  // 2. content = []
  return content;
}

I need help understanding this. Why is content empty on the 2nd comment? From the looks of it, the function starts pushing hash into a NEW variable called content, instead of referencing the content that I explicitly made in the beginning. How do I fix this? Why is javascript scope so confusing.

Also, to fix this, I global variables. WHY can my function have access to a global variable content anywhere in the function, but calling content in the beginning function, it won't have access to certain places.

Eric Chu
  • 1,649
  • 3
  • 20
  • 26

1 Answers1

1

Because $.get is async. The nature of this call is that it goes into the event loop and doesn't modify your current program flow.

You should use callback.

function getContent(type, callback) {
  var content = [];
  $.get(`/${type}.json`, function(data) {
    $.each(data, function(index, hash) {
      content.push(hash);
    });
    callback( content );
 });
}

getContent("items", function( content ) {
   console.log(content);
});

To give you a better example you can also use your flow, but it should look like this :

function getContent(type, callback) {
  var content = [];
  $.get(`/${type}.json`, function(data) {
    $.each(data, function(index, hash) {
      content.push(hash);
    });
    callback();
  });
  return content;
}

var items = getContent("items", function() {
   console.log( items );
});
drinchev
  • 19,201
  • 4
  • 67
  • 93