我一直试图让剩下的代码等待ajax调用在执行之前运行,因为我首先需要数组中的信息。我尝试了多种方法,但我无法弄清楚为什么他们会赢。在这种情况下,似乎使用承诺可能是最好的做法。目前,ajax仍在.done和最终的console.log(3)之后运行。
请参阅以下代码:
$(document).ready(function(){
var selectedChannels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var numberOfChannels = selectedChannels.length;
var onlineChannels = [];
var offlineChannels = [];
function getChannels(){
for (var count = 0 ; count < numberOfChannels; count++) {
$.ajax({
url: "https://wind-bow.hyperdev.space/twitch-api/streams/"+ selectedChannels[count],
type: "get",
dataType: "jsonp",
callback: "?",
data: {
},
success: function(data) {
if (data.stream) {
var logo = data.stream.channel.logo
var twitchName = data.stream.channel.display_name
var details = data.stream.channel.status
var link = data.stream.channel.url
onlineChannels.push(twitchName);
console.log(onlineChannels);
console.log(1);
$(".display-area").append("<div class=\"result-box online\"><img src="+ logo +" alt=\"twitchName\" class=\"profile-img\"></img><div class=\"title\">"+ twitchName +"</div><div class=\"description\">"+ details +"</div>");
}
},
}).done(function(){
});
}
}
/* should run after ajax and onlineChannels array has been populated */
function completeAjax() {
var promised = getChannels();
var promisedComplete = $.when(promised);
promisedComplete.done(function(){
console.log(onlineChannels);
console.log(2);
});
}
completeAjax();
console.log(3)
});
答案 0 :(得分:3)
您可以映射ajax调用并返回promises,然后使用$.when.apply
检查所有ajax调用是否已完成
$(document).ready(function() {
var selectedChannels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var onlineChannels = [];
var offlineChannels = [];
function getChannels() {
return $.map(selectedChannels, function(channel, index) {
return $.ajax({
url : "https://wind-bow.hyperdev.space/twitch-api/streams/" + channel,
type : "GET",
dataType : "jsonp",
callback : "?",
data : {}
}).done(function(data) {
if (data.stream) {
var logo = data.stream.channel.logo;
var twitchName = data.stream.channel.display_name;
var details = data.stream.channel.status;
var link = data.stream.channel.url;
onlineChannels.push(twitchName);
$(".display-area").append("<div class=\"result-box online\"><img src=" + logo + " alt=\"twitchName\" class=\"profile-img\"></img><div class=\"title\">" + twitchName + "</div><div class=\"description\">" + details + "</div>");
}
});
});
}
$.when.apply($, getChannels()).done(function() {
// all done, onlineChannels populated
});
});
答案 1 :(得分:1)
你可以使用你的计数器倒数到零,看看还有多少Ajax调用需要完成:
for (var count = 0 ; count < numberOfChannels; count++) {
$.ajax({
// ...
success: function(data) {
count--; // <!--------- decrease count
// ...
},
}).done(function(){
if (!count) { // <!--------- see if this was the last one finishing.
// All Ajax done.
// ...following tasks are initiated here.
//
}
});
}
要了解其工作原理,请务必了解在循环结束之前未调用success
和done
回调,并且count
已达到最大值。从那时起count
只会减少。