-2

Results I hope to log: [ 'freecodecamp' , 'twitchtv' , 'exercise' ]

I've read a bunch of post regarding Asynchronous situation which explains why I'm getting these "empty [ ]" on the Console:
"empty" meaning it appears like this:[ ],
rathan than this : [ 'freecodecamp' , 'twitchtv' , 'exercise' ].

What I'm getting so far : if console.log(online_streamer) is placed as follow scenarios:

A. (Within getJSON callback) --- logs: undefined, then a couple lines of empty [ ] before printing the final "usable" array with 3 items(gamers names) in it.

B. (Outside forLoop) --- logs: 1 [ ] array with 3-items to show ONLY if I press the arrow down button. Again, (Async situation.)

My Question : Did I misplace the consoe.log or do I need some complete different function to print a usable array like: [ 'item1' , 'item2' , 'item3' ] like the last iteration of scenario A.) ? Thanks guys.

function getOnlineGamers(){
    var online_gamers = [];
    for (var i=0; i<gamers.length; i++){
        //(gamers is a defined array with 11names of 11gamers.)

        $.getJSON(url+"streams/"+ gamers[i]+cid).done(function(data){
            if(data.stream === null){
            }else {
                var name= data.stream.channel.name;
                online_gamers.push(name);
            }
            console.log(online_gamers);  // <--- A 
        });
    };
    console.log(online_gamers); //<--- B 
};

console.log(getOnlineGamers())
Matt
  • 74,352
  • 26
  • 153
  • 180
  • getOnlineGamers() doesn't return anything, so logging it won't log anything useful. You need to use proper "async return" techniques. – Carcigenicate Aug 22 '17 at 11:08
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Carcigenicate Aug 22 '17 at 11:08
  • The first empty array is from `B`, then an `undefined` from `console.log(getOnlineGamers())`, *then* `A` may be logging something. – deceze Aug 22 '17 at 11:09

1 Answers1

0

you have to wait for each resolution, then you can work with the resulting array.

function getOnlineGamers(gamers, cid) {

  return Promise
    .all(gamers.map(function(game) {
       return $
        .getJSON(url + "streams/" + game + cid)
        .then(function(data) {

          return data.stream && data.stream.channel.name;
        })
      ;
    }))
  ;
}    


getOnlineGamers([123, 321, 231], 'foobaz')
  .then(function(names) {

    console.log('names', names);
  })
;
Hitmands
  • 13,491
  • 4
  • 34
  • 69