我想首先在 populateStreamerCards 函数中运行一个AJAX API调用循环,然后在完成后,运行一个针对不同数据的AJAX调用循环。
在阅读 $。时后,似乎我必须从我的第一个函数返回 promise 对象,但我不确定这样做的语法。
var streamers = ["dreadztv", "lirik", "freecodecamp", "LCK1", "ESL_SC2"];
function populateStreamerCards () {
var twitchPassThroughAPI = "https://wind-bow.gomix.me/twitch-api/channels/";
var streamerSection = document.getElementById("streamers");
// Loop through to populate the cards.
for (var i = 0; i < streamers.length; i++) {
// Get data from the 'channels' portion of the API and populate the cards
$.ajax( {
url: twitchPassThroughAPI + streamers[i],
dataType: 'jsonp', // jsonp helps with cross origin error
type: 'GET',
headers: { 'Twitch API App': 'v.1' },
success: function(data) {
alert(JSON.stringify(data, null, 4)); // Shows the whole returned object nicely formatted for debugging
// Populate cards with the channel data
var card = document.createElement('div');
card.className = 'card';
card.id = 'user-' + data.display_name;
// Populate the card with streamer data
card.innerHTML = '<img class="card-img-top" src="' + data.logo + '" alt="Stream Image">\
<div class="card-block">\
<h4 class="card-title">' + data.display_name + '</h4>\
<p class="card-text">' + data.status + '</p>\
<a href="' + data.url +'" class="btn btn-primary">View</a>\
</div>';
// Append the card to the streamer section
streamerSection.appendChild(card);
}
});
}
}
$.when( populateStreamerCards() ).done(function() {
alert('Now it is time to check if they are online');
var twitchPassThroughAPI = "https://wind-bow.gomix.me/twitch-api/streams/";
// Loop through to fade the cards of offline streamers
for (var i = 0; i < streamers.length; i++) {
$.ajax( {
url: twitchPassThroughAPI + streamers[i],
dataType: 'jsonp', // jsonp helps with cross origin error
type: 'GET',
headers: { 'Twitch API App': 'v.1' },
success: function(data) {
if (data.stream == null){
// The streamer is offline. Add the offline class to fade out the card
$( "#user-" + streamer ).addClass( "offline" );
// Change the button text to Offline and disable it
}
}
});
}
});