javascript - For 循环中调用 get JSON 函数时出错

标签 javascript for-loop getjson

我在通过删除循环内的函数来重新格式化 JavaScript 时遇到问题。

这是我的 JavaScript 代码:

$(document).ready(function () {
  //GET TWITCH TV STREAMERS' STATUS AND API CALL

  var twitchTvStreamers = ["FreeCodeCamp", "ESL_SC2", "OgamingSC2", "cretetion", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

  //OUT OF ALL THE TWITCH TV STREAMERS IN A TWITCH TV ARRAY FIND THOSE 8 STREAMERS LISTED
  for (var i = 0; i < twitchTvStreamers.length; i++) {

    //DO A GETJSON ON THIS ARRAY TO RETRIEVE INFORMATION FROM THE VALUES OF THOSE 8 TWITCH TV STREAMERS
    $.getjSON('https://wind-bow.glitch.me/twitch-api/streams' + val, function (st) {
      //var url="https://wind-bow.glitch.me/twitch-api/streams" 

      channelName = val;

      //IF ANY OF THE STATUSES OF THE 8 TWITCH TV STREAMERS ARE EQUAL TO NULL, OR OFFLINE, THEN DO SOMETHING
      if (st.stream === null) {
        //GET JSON INFO OF THOSE OFFLINE STREAMERS
        $.getjSON('https://wind-bow.glitch.me/twitch-api/channels' + val, function (ch) {

          channelID = ch.Display_name;
          channelLogo = ch.logo;
          channelUrl = ch.url;
          streamContent = ch.content;

          //POST INFO TO DISPLAY AREA OF WEB APP (...ADD OTHER STUFF TO THIS APPEND LATER)
          $('#offline').append('<div class="TV-screen">');
        });

      } else
        //REPEAT SAME SCENARIO AS USED FOR OFFLINE STREAM STATUS    
        $.getjSON('https://wind-bow.glitch.me/twitch-api/channels' + val, function (ch) {

          channelID = ch.Display_name;
          channelLogo = ch.logo;
          channelUrl = ch.url;
          streamContent = ch.content;

          $('#online').append('<div class="TV-screen">');
        });

    }               

//借助来自: https://www.youtube.com/watch?v=Nm2bXBlELZU&list=PLHdCowjFIBmJwYL9tPZOkn6CIVLg6Z36a 的帮助等等等等……

我将上面的代码放入 www.jshint.com它给出了以下结果:

三个警告”:

  1. 11 不要在循环内创建函数。
  2. 42 应为 ')',但看到的是 ''。
  3. 49 不可恢复的语法错误。 (100% 扫描)。

如何重新格式化我的代码(第 11 行)以包含我的 get JSON 函数,但又不在循环内?

最佳答案

您在语法、打字错误、错误的函数名称以及异步调用的延迟返回的占位符的错误使用方面存在大量错误。错误摘要如下。同时,运行代码以确保它确实有效。

$(document).ready(function(){
// Who we want to stalk today
var twitchTvStreamers=["FreeCodeCamp", "ESL_SC2", "OgamingSC2", "cretetion", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

// Get the status of each channel using the getChannelInfo() function
for(channel of twitchTvStreamers){
    getChannelInfo(channel);
    }
});

// This function gets the status of each channel
// and, depending whether it is online or offline, 
// calls the appendInfo() function with the online/offline parameter
var getChannelInfo = channel => { 
    $.getJSON('https://wind-bow.glitch.me/twitch-api/streams/' + channel)
    .done(function(info) {
        if (info.stream === null) appendInfo(channel,'offline');
        else appendInfo(channel,'online');
    });
}

// This function gets info on whether the channel is online or offline. 
// Depending on this status, it gets the channel info 
// and appends it in the respective `<div>`
var appendInfo = (channel,target) => {
    $.getJSON('https://wind-bow.glitch.me/twitch-api/channels/' + channel)
        .done( function(ch){
            channelID = ch.display_name;
            channelLogo = ch.logo;
            channelUrl = ch.url;
            streamContent = ch.content;
            $('#'+target).append('<div class="TV-screen">'+channel+' is '+target);
        });    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="online"></div>
<div id="offline"></div>

所以,您的代码问题是:

  1. channel = val;设置 channel 变量,而不是 val 变量。 val = channel会设置 val 变量,但这在您的代码中也不起作用。您可以将 val 设置为 val = twitchTvStreamers[i];

  2. getjSON应拼写为 getJSON - 大小写很重要!

  3. ch.Display_name不起作用,因为返回的对象键拼写为 display_name 。再次强调,请谨慎对待您的案件。

  4. $('#offline').append('<div class="TV-screen">'); - 这只是添加了一个空白 <div>#offline元素。您还需要在此处包含一些特定于 channel 的信息。

  5. 而且,最重要的是,您必须准确了解 JS Promise作品。我读到的最后一个最好的资源是 Kyle Simpson 的 Asynch & Performance他的你不懂 JS 系列的书。 jQuery 的 getJSON使用 Promise 接口(interface),因此了解底层技术绝对有帮助。

简而言之 - 当您制作 asynch call 时,响应需要一段时间才能完成,同时执行其他代码。例如,您有一个名为 status 的变量,并且您正在对 Twitch channel foobar 的状态进行 API 调用。在 API 响应返回之前,您的代码已经打印出 <div id="foo"><div id="bar">在页面上。然后状态返回, channel foo 的状态返回为 在线 并设置 status变量为“在线”。然后,bar 的状态返回为“离线”并设置 status变量为离线。而且,如果处理不当,JS 将返回最后一个值(离线),并且它适用于所有元素。

您必须能够进行调用并将其结果 promise 给正确的 DOM 元素。我是这样做的:

  • 获取状态
    • 如果在线,获取 channel 详细信息,生成 DOM 元素,附加到“在线”div
    • 如果离线,获取 channel 详细信息,生成 DOM 元素,附加到“离线”div

这里生成和附加 DOM 元素的顺序与进行 AJAX 调用和获取结果的顺序不交叉。最简单的方法是将这个序列分解为单独的函数并按每个步骤调用它们,我就是这么做的。

关于javascript - For 循环中调用 get JSON 函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48859596/

相关文章:

javascript - 0x800a138f - JavaScript 运行时错误 : Unable to get property 'fn' of undefined or null reference

javascript - 我如何知道自定义 soundcloud 播放器正在播放什么?

javascript - 表不再更新到 firebase、React

javascript - 如何同时从多个url获取数据?

c# - 仅当在循环的所有迭代中都满足条件时才执行操作

jquery - getJSON Facebook 调用在 IE 中不起作用

javascript - 无法从 json-p 调用访问数据

python - 将字符串转换为嵌套列表

ios - 当 for 循环从 NSArray 到达 NSNotFound 时如何中断

javascript - 使用 getJSON 函数读取 while 循环数据