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.