本文介绍了在For循环中获取JSON函数的错误调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在从循环中删除我拥有的函数时,我在重新格式化JavaScript时遇到问题.

I'm having a problem reformatting my JavaScript by removing a function that I have from within a loop.

这是我的JavaScript代码:

Here is my JavaScript code:

$(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 等).

//with help from: https://www.youtube.com/watch?v=Nm2bXBlELZU&list=PLHdCowjFIBmJwYL9tPZOkn6CIVLg6Z36a, etc. etc......

我将上面的代码放入 www.jshint.com 中,结果如下:

I placed the above code into www.jshint.com and it gave the following results:

三个警告":

  1. 11不要在循环中创建函数.
  2. 42应该是')',而是看到了''.
  3. 49无法恢复的语法错误. (已扫描100%).

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

How can I reformat my code (at line 11) to include my get JSON function, but without it being within the loop?

推荐答案

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

You've got a large number of errors in syntax, typos, wrong function names and wrong usage of the placeholders for deferred returns of the asynch calls. A summary of the errors is below. Meanwhile, run the code to make sure that it actually works.

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

因此,您的代码问题是:

So, your problems with the code were:

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

  1. channel = val; sets the channel variable, not the val variable. val = channel would set the val variable but that wouldn't work in your code either. You could set val like val = twitchTvStreamers[i];

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

getjSON should be spelled as getJSON - case matters!

ch.Display_name将不起作用,因为返回的对象键被拼写为display_name.同样,请谨慎处理您的案件.

ch.Display_name won't work as the returned object key is spelled as display_name. Again, be careful with your cases.

$('#offline').append('<div class="TV-screen">');-这仅将空白<div>添加到#offline元素.您还希望在此处包括一些通道专用信息.

$('#offline').append('<div class="TV-screen">'); - this just adds a blank <div> to the #offline element. You would want to include some of the channel-specifit information here as well.

最重要的是,您必须确切了解 JS Promise 有效.我在此阅读的最后一个最佳资源是Kyle Simpson的异步&他的您不了解JS 系列中的Performance 一书. jQuery的getJSON使用Promise接口,因此了解底层技术肯定会有所帮助.

And, most important of all, you gotta understand exactly how JS Promise works. The last best resource I read on this was Kyle Simpson's Asynch & Performance book from his You don't know JS series. jQuery's getJSON uses the Promise interface, so knowing the underlying technology definitely helps.

简而言之-当您制作异步调用,响应需要一段时间才能通过,与此同时,其他代码也将执行.例如,您有一个名为status的变量,并且正在对Twitch通道 foo bar 的状态进行API调用.在API响应返回之前,您的代码已经在页面上打印出<div id="foo"><div id="bar">.然后状态返回,通道 foo 的状态返回为 online ,并将status变量设置为"online".然后, bar 的状态返回为脱机",并将status变量设置为脱机.而且,如果处理不当,JS将返回此最后一个值(脱机),并将其应用于您的所有元素.

In a nutshell - when you are making an asynch call, the response takes a while to come through and meanwhile, other code executes. For example, you have a variable called status, and you are making an API call for the statuses of Twitch channels foo and bar. Until the API response comes back, your code already prints out <div id="foo"> and <div id="bar"> on the page. Then the statuses come back, status of channel foo comes back as online and sets the status variable as 'online'. Then, status of bar comes back as 'offline' and sets status variable to offline. And, if not handled properly, JS returns this last value (offline), and it applies to all of your elements.

您必须能够进行调用并将其结果承诺给正确的DOM元素.我这样做如下:

You have to be able to make the call and promise its result to the correct DOM element. I did it as following:

  • 获取状态
    • 如果在线,则获取频道详细信息,生成一个DOM元素,并附加到在线" div
    • 如果处于离线状态,请获取频道详细信息,生成一个DOM元素,然后附加到离线" div
    • Get the status
      • If online, get the channel details, produce a DOM element, append to the 'online' div
      • If offline, get the channel details, produce a DOM element, append to the 'offline' div

      此处,生成和附加DOM元素的顺序与进行AJAX调用和获取结果的顺序不交叉.将这个序列分解为单独的函数,并按照我的每一步进行调用是最简单的.

      Here the sequence of producing and appending DOM elements does not cross the sequence of making AJAX calls and getting the results. It is the easiest to break this sequence down to separate functions and call them by each step, which I did.

      这篇关于在For循环中获取JSON函数的错误调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:02