0

I have a an API callback function populating an array 'users', and when I console.log the array, all the elements are there, but when I try to get the length of the array, it is 0. Also accessing any part of the array it returns undefined. --> I get that this is asynchronous, however the suggested duplicate doesn't explain why the array is populating, and yet I can't access any part of it other than to log the entire array.

Can someone explain to me why? and offer some advice if i'm doing it all wrong? Thanks in advance

var users = [];

var twitchUsers = ["ogamingsc2","nightblue3","asiagodtonegg3be0", "freecodecamp", "brunofin", "cockadoodledo"];

buildURL = function(type, user){
    var url = 'https://api.twitch.tv/kraken/' + type + '/' + user + '?callback=?';
    return url;
}

function getRemainingData(element, index, array){
$.getJSON(buildURL("streams", element), function(streamData){

    if(streamData.stream){
        var game = streamData.stream.channel.game;
        var status = streamData.stream.channel.status;

        users.push({name:element, game:game, status:status, error:""});

    }
    else if(!streamData.stream && !streamData.error){
        users.push({name:element, game:"", status:"", error:""})
    }
    if(streamData.error){
        var error = streamData.error
        users.push({name:element, game:"", status:"", error:error});
    }

});  
}

console.log(users); //returns array as attached below
console.log(users[0]); //returns unidentified
console.log(users.length); //returns 0

console.log(users)

  • Please add the `console.log` output to your post – bviale Apr 07 '16 at 14:08
  • 1
    You may want to put the console logs *inside* the function. `$.getJSON` is asynchronous – j08691 Apr 07 '16 at 14:09
  • If that's a copy/paste then it won't work as your two `console.log` calls are executing before you've got any data returned. Can you show us what they output (as suggested by @bviale), but also show the output of `console.log(users);`? – Reinstate Monica Cellio Apr 07 '16 at 14:10
  • Just added the console.log as a link – David Argent Apr 07 '16 at 14:12
  • I didn't understand how to interpret the answer to the question, which this is apparently a duplicate of so I've abandoned ship and changed approach. Probably out of my depth, but thanks to the ones who tried to help. – David Argent Apr 08 '16 at 08:17

1 Answers1

1

You're accessing the array before it gets populated.

$.getJSON() is an asynchronous operation and you're trying to access the array it populates right after calling it, but before it has actually populated the array.

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100