1

So I'm making a couple of ajax calls and I ultimately want to build an array of objects that contain the relevant values I need. Unfortunatley I've run into something weird. My first ajax call returns an the Array full of objects I'm looking for, but when I call length on the array I get zero. Here's the relevant code (in the code 'followings' is an array of followings the user has):

function followingsJSON(followings) {
  var followingObject = [];

  for (var i in followings) {
    var query = "https://wind-bow.glitch.me/twitch-api/users/" + 
followings[i];

    $.ajax({

      url: query,
      type: "GET",
      datatype: "json"

    }) .done(function(json){
      if (json.display_name) {
        followingObject.push({
          'display_name' : json.display_name,
          'logo' : json.logo,
          '_id' : json._id
        });
      } else {
        followingObject.push({
          'display_name' : null
        });
      }
    })
  };
  console.log(followingObject);
  console.log(followingObject.length);
  }

Using chrom dev tools I can see from the console logs that followingObject is:

[]
0: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
length: 9
__proto__: Array(0)

So the array has the objects I want and the array derives its prototype methods from Array so length should work on it. But the console.log(followingObject) gives me 0.

Anybody know why?

Stephen Agwu
  • 1,013
  • 2
  • 15
  • 29

1 Answers1

2

I moved the console.log to the done function

function followingsJSON(followings) {
    var followingObject = [];

    for (var i in followings) {
        var query = "https://wind-bow.glitch.me/twitch-api/users/" +
            followings[i];

        $.ajax({

            url: query,
            type: "GET",
            datatype: "json"

        }) .done(function(json){
            if (json.display_name) {
                followingObject.push({
                    'display_name' : json.display_name,
                    'logo' : json.logo,
                    '_id' : json._id
                });
            } else {
                followingObject.push({
                    'display_name' : null
                });
            }
            console.log(followingObject);
            console.log(followingObject.length);
        })
    };
}

The console.log is synchronus while the ajax call gets executed asynchronus, meaning commands after the ajax call get executed before the ajax call is finished -> no results in console.log yet

Marvin Fischer
  • 2,552
  • 3
  • 23
  • 34