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!
Based on your current code, the most straightforward way would be to set $.ajax’s
asyncoption 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.: