gpt4 book ai didi

javascript - 使用 promises 获取 ajax 数据

转载 作者:行者123 更新时间:2023-11-30 09:42:36 25 4
gpt4 key购买 nike

我一直在尝试让我的代码的其余部分在执行之前等待 ajax 调用运行,因为我首先需要数组中的信息。我尝试了多种方法,但我无法弄清楚为什么他们不会。在这种情况下,使用 promises 似乎是最佳实践。目前 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)
});

最佳答案

您可以映射 ajax 调用并返回 promise ,然后使用 $.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
});

});

关于javascript - 使用 promises 获取 ajax 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40465190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com