我正在尝试循环遍历一组团队来获取玩家数据并将数据传递给一个对象。我的 ajax 调用获取文件。循环遍历所有团队后,我想用收集的数据编写日志。问题是 writeLog() 被立即调用 - 我认为 - 没有等待循环完成。这是吊装问题吗?回调问题? for 循环完成后如何将代码重构为 writeLog() ?
(function(){
$('#generate-report').on('click', function(){
var logObj = {
playerCount: 0,
firstNameArray: [],
lastNameArray: [],
firstNameCharCount: 0,
lastNameCharCount: 0,
resultFirst: 0,
resultLast: 0,
freqReportFirst: "First name\n",
freqReportLast: "Last name\n",
freqObjFirst: {},
freqObjLast: {},
}
var url = "http://feeds.nfl.com/feeds-rs/roster/";
var teams = new Array("3800", "0200", "0325", "0610", "0750", "0810", "0920", "1050",
"1200", "1400", "1540", "1800", "2120", "2200", "2250", "2310",
"2700", "3000", "3200", "3300", "3410", "3430", "2520", "3700",
"3900", "4400", "4600", "4500", "2510", "4900", "2100", "5110"
);
//var teams = new Array("3800"); // For testing
for(var i=0; i<teams.length; i++){
console.log(teams[i]);
$.ajax({
url: url + teams[i] + ".json",
type: 'GET',
success: function(response){
processPlayerNames(response, logObj);
},
error: function(response){
console.log(response);
}
});
};
writeLog(logObj);
});
})();
最佳答案
$.ajax()
异步返回结果。您可以将 $.ajax()
调用推送到数组,然后在 Promise 数组上使用 Promise.all()
, .map()
对象,或者使用 $.when()
、Function.prototype.apply()
、.map()
在调用之前执行所有异步任务.then()
处的 writeLog()
链接到表示从 $.when()
调用返回的 jQuery Promise 对象的变量。
var requests = $.when.apply(null, teams.map(function(team) {
return $.ajax({
url: url + team + ".json",
type: 'GET',
success: function(response){
processPlayerNames(response, logObj);
}
});
}));
requests.then(function() {
writeLog(logObj)
}, function(response){
console.log(response);
});
关于javascript - 提升或回调问题?在 writeLog() 之前完成 for(loop) 但日志在完成之前写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39842124/