简体   繁体   中英

How to run code after separate ajax calls have completed within an each loop

My HTML code:

<!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>

My JS code:

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

I need the following code to run after the outer and inner ajax requests have completed all of their iterations:

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

As you might notice, I've tried implementing the advice here: Is it possible to run code after all ajax call completed under the for loop statement?

...but that seems only to work when there is just one ajax call in the $.each() loop.

How do I get this to work with two separate ajax requests within my $.each() loop, each with multiple iterations? Currently only the live streams delivered by the outer ajax iterations are showing in my list.

Use the fact that $.ajax returns a promise to your advantage.

in .then callback, returning a value resolves the promise returned by .then - however, returning a Promise will mean that .then will wait on the returned Promise and resolve to that value

This also means, by using Array#map, no need for pushing to an array or array[i] = whatever type code - it's all handled by the .map and the resolved value of the 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));
        });
    });
});

I was thinking of using promise based solution, but your scenario seems to be solved by adding 2 if clause(can be reduced to 1 if used promise). I have put your render logic in a function and calling that when all ajax request comlpleted, that's it.

 $( 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
      };
      if(channels.length === allStreams.length){
        allStreamsFetched();
      }

    } 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
          };

          if(channels.length === allStreams.length){
            allStreamsFetched();
          }
        } // close inner success
      }); // close inner $.ajax()
    } // close else
  } // close outer success
}); // close outer $.ajax()
arr.push(xhr);


}); // close $.each()


function allStreamsFetched(){
 console.log(allStreams);
 $.each(allStreams, function(i, stream) {
 $ul.append(Mustache.render(listTemplate, stream));
});
 }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM