Array.length是3但是记录了一个空的"数组

时间:2017-08-22 11:04:54

标签: javascript arrays for-loop asynchronous twitch

结果我希望记录:[' freecodecamp' ,' twitchtv' ,'运动' ]

我已经阅读了一些关于Asynchronous situation的帖子,这解释了为什么我会得到这些"空[]"在控制台上:
"空"意思是这样的:[],比这更大:[' freecodecamp' ,' twitchtv' ,'运动' ]。

到目前为止我 :如果 console.log(online_streamer) 按以下方式放置:

一个。 (在getJSON回调中)--- logs:undefined,然后在打印最终"可用"之前输入几行empty []。数组中包含3项(游戏玩家名称)。

B中。 (在forLoop之外)---日志:1 []数组只显示3项,如果我按下箭头按钮。再次,(Async situation.)

我的问题: 我是否错放了consoe.log或者我是否需要一些完全不同的功能来打印可用的数组,如:[' item1' ,' item2' ,' item3' ]就像场景的最后一次迭代 A。)?谢谢你们。

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())

1 个答案:

答案 0 :(得分:0)

你必须等待每个决议, 那么你可以使用生成的数组。

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);
  })
;
相关问题