Twitch TV - Cannot access my array variables after successful ajax call

I have made $.getJSON requests two the two apis and received back an array with eight arrays inside. Each of the inner arrays contains two objects, one for user data and another for the stream data.

Problem is I an unable to access any data from the internal array as shown in the code below.

$(document).ready(function() {
  var users = [
    "ESL_SC2",
    "OgamingSC2",
    "cretetion",
    "freecodecamp",
    "storbeck",
    "habathcx",
    "RobotCaleb",
    "noobs2ninjas"
  ];
  getUserInfo(users);
});

//Getting user info from the two urls : with parameter streams and user
function getUserInfo(users) {
  allData = [];
  users.forEach(element => {
    let info = [];
    $.getJSON(
      `https://wind-bow.gomix.me/twitch-api/users/${element}?callback=?`,
      function(data) {
        info[0] = data;
      }
    );

    $.getJSON(
      `https://wind-bow.gomix.me/twitch-api/streams/${element}?callback=?`,
      function(data) {
        info[1] = data;
      }
    );

    allData.push(info);
  });
  renderResponse(allData);
}
// Render data to html
function renderResponse(allData){
  let output = ``;
  console.log(allData);//works
  //console.log(allData[0][0].display_name);//=> Checking to see if I can access the data but getting an uncaught type error instead

  allData.forEach(element => {
    console.log(element[0].display_name);
  });
}```

Kindly help..a bit frustrated.

Thats because $.getJSON is an asynchronous function. By asynchronous i mean the callback doesnt run till the data is fetched from the server. But this doesnt stop the execution process as the code after the function continues with its execution.
So in your case you are trying to loop over the array even before the array is filled with data. Therefore the property is undefined.

To solve this you can put the second $.getJSON call inside the callback function of first one and then console log the property inside the callback of the callback function of the second one.

Thanks a lot @vikrant17 …Worked like a charm. On to styling and adding some more functionality.

Glad I could help :slight_smile: