0

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

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Simple and accurate explanation, I'll have to keep this in mind. Thanks adriancarriger
Glad it helped!
1

You would have to use a callback function to get the data out of the function and manipulate the data where sendMethedata is your callback function

var dataArray = [];

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

  })
    .done(function( data ) {


   var yearsData = data['data']


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


    });
    sendMethedata(dataArray);

 });

function sendMethedata(data){
console.log(data)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.