2 ajax在for循环中调用

时间:2017-11-08 08:33:24

标签: javascript jquery ajax

我创建了一个与Twitch API交互的网页。该应用程序基本上显示了一个抽搐用户的名称,徽标以及他们是离线还是在线。

要做到这一点。我做了两个AJAX调用:

  var twitches = [
    "freecodecamp",
    "orb",
    "medrybw",
    "storbeck",
    "terakilobyte",
    "habathcx",
    "RobotCaleb",
    "thomasballinger",
    "noobs2ninjas",
    "beohoff"
  ];

  // Retrieve the username and logo of the user
for(x=0;x < twitches.length; x++){
      $.ajax({
        url:"https://api.twitch.tv/kraken/users/"+ twitches[i] + "?client_id=fmg7qm7vtgxozyr7dj2icwrumdb186",
        type: "GET",
        dataType: "jsonp",
        success: function(x) {
          if (x.logo == null) {
            x.logo =
              "http://www.dotcomsolicitors.com/wp-content/uploads/sites/491/2017/08/user-icon-300x300.png";
          }
          $(".tbody").append(
            "<tr><td>" +
              '<a href="https://go.twitch.tv/' +
              x.name +
              '">' +
              '<img src="' +
              x.logo +
              '"/></a></td><td><p>' +
              '<a href="https://go.twitch.tv/' +
              x.name +
              '">' +
              x.name +
              '</a></p></td><td class="onOroff"></td></tr>'
          );
        }
      });
}

并且此AJAX调用检查用户是否在线。如果x.stream === null,则表示用户处于脱机状态,因此将在最后一列中附加无符号。但我的循环似乎有问题,我不知道如何解决它。 codepen是https://codepen.io/mrsalami/pen/yPaOqO

for(x=0;x < twitches.length; x++){
$.ajax({
    url:"https://api.twitch.tv/kraken/streams/"+ twitches[i] + "?client_id=fmg7qm7vtgxozyr7dj2icwrumdb186",
    type: "GET",
    dataType: "jsonp",
    success: function(x) {
      console.log(x.stream);

      if (x.stream === null) {
        $(".onOroff").append(
          '<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/No_sign.svg/300px-No_sign.svg.png" alt="Image result for no symbol png"/>');
      } else {
        $(".onOroff").append(
          '<img src="https://www.shareicon.net/download/2015/10/24/136117_ok_300x300.png" alt="Image result for yes symbol png"/>'
        );
      }
    }
  });

}

控制台日志:

null
null

Object {
  _id: 26678888912,
  _links: Object {
    self: "https://api.twitch.tv/kraken/streams/medrybw"
  },
  average_fps: 24.025974026,
  channel: Object {
    _id: 50332395,
    _links: Object {},
    background: null,
    banner: null,
    broadcaster_language: "en",
    created_at: "2013-10-18T22:13:12Z",
    delay: null,
    display_name: "MedryBW",
    followers: 23013,
    game: "StarCraft",
    language: "en",
    logo: "https://static-cdn.jtvnw.net/jtv_user_pictures/medrybw-profile_image-19fce7e1b0d6c194-300x300.jpeg",
    mature: false,
    name: "medrybw",
    partner: false,
    profile_banner: null,
    profile_banner_background_color: "",
    status: "24/7 Classic Starcraft VoD stream 2000-2012 (6344 VoDs)",
    updated_at: "2017-11-08T08:33:30Z",
    url: "https://www.twitch.tv/medrybw",
    video_banner: null,
    views: 854932
  },
  created_at: "2017-11-08T04:26:27Z",
  delay: 0,
  game: "StarCraft",
  is_playlist: false,
  preview: Object {
    large: "https://static-cdn.jtvnw.net/previews-ttv/live_user_medrybw-640x360.jpg",
    medium: "https://static-cdn.jtvnw.net/previews-ttv/live_user_medrybw-320x180.jpg",
    small: "https://static-cdn.jtvnw.net/previews-ttv/live_user_medrybw-80x45.jpg",
    template: "https://static-cdn.jtvnw.net/previews-ttv/live_user_medrybw-{width}x{height}.jpg"
  },
  stream_type: "live",
  video_height: 768,
  viewers: 22
}

​
Object {
  _id: 26669328176,
  _links: Object {
    self: "https://api.twitch.tv/kraken/streams/orb"
  },
  average_fps: 60,
  channel: Object {
    _id: 20519306,
    _links: Object {},
    background: null,
    banner: null,
    broadcaster_language: "en",
    created_at: "2011-02-17T07:14:53Z",
    delay: null,
    display_name: "Orb",
    followers: 166319,
    game: "Call of Duty: WWII",
    language: "en",
    logo: "https://static-cdn.jtvnw.net/jtv_user_pictures/orb-profile_image-076d545e806d2190-300x300.png",
    mature: false,
    name: "orb",
    partner: true,
    profile_banner: "https://static-cdn.jtvnw.net/jtv_user_pictures/0e56159f562dcf9f-profile_banner-480.png",
    profile_banner_background_color: "",
    status: "24/7 Race to Prestige  Annual Call of Duty Marathon | OFFICIAL !Merch  | !DXRacer Giveaway | Powered by: !Elgato !Razer !Nvidia",
    updated_at: "2017-11-08T08:33:25Z",
    url: "https://www.twitch.tv/orb",
    video_banner: "https://static-cdn.jtvnw.net/jtv_user_pictures/orb-channel_offline_image-0d0763efc52d70f3-1920x1080.png",
    views: 16628568
  },
  created_at: "2017-11-06T22:45:13Z",
  delay: 0,
  game: "Call of Duty: WWII",
  is_playlist: false,
  preview: Object {
    large: "https://static-cdn.jtvnw.net/previews-ttv/live_user_orb-640x360.jpg",
    medium: "https://static-cdn.jtvnw.net/previews-ttv/live_user_orb-320x180.jpg",
    small: "https://static-cdn.jtvnw.net/previews-ttv/live_user_orb-80x45.jpg",
    template: "https://static-cdn.jtvnw.net/previews-ttv/live_user_orb-{width}x{height}.jpg"
  },
  stream_type: "live",
  video_height: 864,
  viewers: 624
}
null
null
null
null
null
null

1 个答案:

答案 0 :(得分:3)

基本上你的代码是一个很大的竞争条件。在一个ajax回调中,您创建一个表格单元格,而在另一个中,您尝试将某些内容附加到空单元格。如果第一个在第二个之前返回,那么所有都应该工作。如果没有,则第二个附加的空单元格没有。

重新组织您的代码以使用Promises,并使用Promise.all等待两者都返回。一旦发生这种情况,您可以在一个地方创建您的内容。

像这样。

var twitches = [...];// your array
for(var i=0;i<twitches.length;i++){
    Promise.all([
        $.ajax(...),  // first ajax call, without the success callback
        $.ajax(...)   // second ajax call, without the success callback
    ]).then(function(results){
       var usernameAndLogoResult = results[0];
       var statusResult = results[1];
       // build your html here
    });
}
相关问题