每个循环完成后执行函数
嘿, 我正在开发一个 jQueryeach() 循环,其中包含 ajax 请求和 setTimeout。这给我带来了程序流程的一些问题。
xml_queries: function (data) {
var values = [];
// ...
$.each(data, function(index, value) {
// ...
// Start xml query
var i = 0;
get_data(value.value);
function get_data(value) {
$.ajax({
type: 'POST',
url: '/admin/scanner/get_music_data/' + value,
dataTaype: 'json',
success: function(response) {
if ( response === 'FALSE' ) {
// Start recursion - up to 3 Retries
if ( ++i <= 3 ) {
setTimeout(function() {
get_data();
}, 100);
} else {
// ...
}
} else {
values.push(response);
}
}
});
}
});
// return values;
console.log(values);
}
我的问题是最后一行中的 console.log() 立即被触发(当循环仍在处理数据时)。难道没有简单的方法可以等待循环完成吗? \:
此致!
Hey there,
I'm working on a jQuery each()-loop containing an ajax-request an a setTimeout. That's giving me some issues with the program flow.
xml_queries: function (data) {
var values = [];
// ...
$.each(data, function(index, value) {
// ...
// Start xml query
var i = 0;
get_data(value.value);
function get_data(value) {
$.ajax({
type: 'POST',
url: '/admin/scanner/get_music_data/' + value,
dataTaype: 'json',
success: function(response) {
if ( response === 'FALSE' ) {
// Start recursion - up to 3 Retries
if ( ++i <= 3 ) {
setTimeout(function() {
get_data();
}, 100);
} else {
// ...
}
} else {
values.push(response);
}
}
});
}
});
// return values;
console.log(values);
}
My problem is that the console.log() in the last line is fired immediatly (while the loop is still processing data). Isn't there any easy possibility to wait for the loop to finish? \:
Best regards!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您当前的代码,最直接的方法是将 $.ajax 的
async
选项设置为 false,以强制同步请求,导致 JavaScript 等待其完成,然后再继续执行后续语句(它不会对异步请求执行此操作)。这将在每个请求期间阻止您的浏览器(恶心)。另一种方法是重新设计您的应用程序,以便从第一个 ajax 调用的成功回调中调用下一个 ajax 调用,例如:
Based on your current code, the most straightforward way would be to set $.ajax's
async
option to false, to force a synchronous request, causing JavaScript to wait for it to complete before continuing to execute the subsequent statements (it won't do this for asynchronous requests).That will block your browser for the duration of each request (yuck). Another way to do it would be to redesign your application such that the next ajax call is called from within the success callback of the first, e.g.: