如何在每个循环内完成单独的ajax调用后运行代码

时间:2017-01-21 06:09:08

标签: javascript ajax each

我的HTML代码:

{"body" : $input.body}

我的JS代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
    <ul id="output">
    <template id="list-template">
      <a href="{{url}}" target="_blank">
        <li>
          <p><strong>{{name}}</strong></p>
          <p><img src="{{logo}}" alt="{{name}} logo"></p>
        </li>
      </a>
    </template>
  </ul>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.js"></script>

</body>
</html>

在外部和内部ajax请求完成所有迭代后,我需要运行以下代码:

 $( document ).ready(function() {

  var $ul = $('#output');
  var listTemplate = $('#list-template').html();
  var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
  var allStreams = [];
  var arr = [];


  $.each(channels, function(i, channelName){
    var xhr = $.ajax({
      url: 'https://wind-bow.gomix.me/twitch-api/streams/' + channelName,
      dataType: 'jsonp',
      success: function(data) {

        if (data.stream) { // i.e. if it's not null and currently streaming
          allStreams[i] = {
            name: data.stream.channel.display_name,
            url: data.stream.channel.url,
            logo: data.stream.channel.logo,
            status: data.stream
          };
        } else { // i.e. it's not currently streaming, do a separate request to get the channel info.
          $.ajax({
            url: 'https://wind-bow.gomix.me/twitch-api/channels/' + channelName,
            dataType: 'jsonp',
            success: function(channelData) {
              allStreams[i] = {
                name: channelData.display_name,
                url: channelData.url,
                logo: channelData.logo
              };
            } // close inner success
          }); // close inner $.ajax()
        } // close else
      } // close outer success
    }); // close outer $.ajax()
    arr.push(xhr);


  }); // close $.each()

  console.log(allStreams);

  $.when.apply($, arr).then(function(){
    $.each(allStreams, function(i, stream) {
      $ul.append(Mustache.render(listTemplate, stream));
    });
  })

/* deleted accounts
  - brunofin
  - comster404
*/



}); // close .ready()

您可能会注意到,我已尝试在此处实施建议:Is it possible to run code after all ajax call completed under the for loop statement?

...但是,当$ .each()循环中只有一个ajax调用时,这似乎才有用。

如何在$ .each()循环中使用两个单独的ajax请求,每个都有多次迭代?目前只有外部ajax迭代提供的实时流在我的列表中显示。

2 个答案:

答案 0 :(得分:2)

使用$ .ajax为您的优势返回承诺的事实。

在.then回调中,返回一个值可以解析.then返回的承诺 - 但是,返回一个Promise意味着.then将等待返回的Promise并解析为该值

这也意味着,通过使用Array#map,无需推送到数组或数组[i] =任何类型代码 - 它都由.map处理并且已解决的promises值

$(document).ready(function() {
    var $ul = $('#output');
    var listTemplate = $('#list-template').html();
    var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
    var arr = channels.map(function(channelName) {
        return $.ajax({
            url: 'https://wind-bow.gomix.me/twitch-api/streams/' + channelName,
            dataType: 'jsonp'
        }).then(function(data) {
            if (data.stream) { // i.e. if it's not null and currently streaming
                return {
                    name: data.stream.channel.display_name,
                    url: data.stream.channel.url,
                    logo: data.stream.channel.logo,
                    status: data.stream
                };
            } else { // i.e. it's not currently streaming, do a separate request to get the channel info.
                return $.ajax({
                    url: 'https://wind-bow.gomix.me/twitch-api/channels/' + channelName,
                    dataType: 'jsonp'
                }).then(function(channelData) {
                    return {
                        name: channelData.display_name,
                        url: channelData.url,
                        logo: channelData.logo
                    };
                });
            }
        });
    });

    $.when.apply($, arr).then(function() {
        var allStreams = [].slice.call(arguments);
        $.each(allStreams, function(i, stream) {
            $ul.append(Mustache.render(listTemplate, stream));
        });
    });
});

答案 1 :(得分:0)

我正在考虑使用基于承诺的解决方案,但您的方案似乎通过添加2 if子句来解决(如果使用了promise,则可以减少到1)。我把你的渲染逻辑放在一个函数中,并在所有ajax请求完成时调用它,就是这样。

@page