wyattwade wyattwade - 7 days ago 5
Ajax Question

difficulty pushing data to an array during async request

In the following code, I'm wondering why my console.log(dataArray) displays an empty array. I think the console.log may be called before the ajax request is finished pulling data. If this is the case, is there any way to wait for the ajax request to finish before calling console.log ?

var dataArray = [];

var gdpAPI = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json";
$.getJSON( gdpAPI, {
format: "json",
async: false

})
.done(function( data ) {


yearsData = data['data']


$.each(yearsData, function(i){
dataArray.push(yearsData[i]);


})


});

console.log(dataArray);


Thank you in advance.
Wyatt

Answer

Async Code

You're right that the console.log was called before the request finished. Just put your log statement inside of the .done section and it will work.

Working Fiddle

var dataArray = [];

var gdpAPI = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json";
$.getJSON(gdpAPI, {
    format: "json",
    async: false

  })
  .done(function(data) {


    yearsData = data['data']

    $.each(yearsData, function(i) {
      dataArray.push(yearsData[i]);


    })
		console.log('length: ' + dataArray.length,dataArray);

  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Comments