Zachary Zachary - 3 months ago 10
Javascript Question

Returning empty array when page loads

I'm currently learning to use API's. I'm retrieving data from my Github repo. I'm trying to have the script load the JSON info into the githubData variable. But when I log the githubData variable to console it returns an empty array.
Yet, if I create a new variable with the exact same function after the page is loaded the script works exactly as it should.
My question is why isn't the data loading into the variable when the page loads? Here's my code:

var githubAPI = 'https://api.github.com/repos/zacharysohovich/ticTacToe/readme';
var items = {};
jQuery.ajax({
url: githubAPI,
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
$.each(resultData, function(key,val) {
items[key] = val;
});
}
});
var githubData = $.map(items,function(k,v) {
return ("<p>" + k + ": " + v + "</p>");
});

Answer

The problem is that its an asynchronous call meaning that once it fires of the request it goes onto the next piece of code. Once it gets to githubData items is still an empty object because the api response hasn't been received yet. I would instantiate the githubData variable right below var items = {} like so

var items = {} var githubData; and then in the success: function after you do the $.each you can put the

githubData = $.map(items,function(k,v) { return ("<p>" + k + ": " + v + "</p>"); });

this ensures that the api call has finished and items should have something in it as long as the response came back with something