Есть гораздо лучший способ сделать это, чем использовать синхронные вызовы ajax. JQuery AJAX возвращает отложенное, так что вы можете просто использовать конвейерную цепочку, чтобы убедиться, что каждый вызов AJAX завершается до следующего запуска. Вот рабочий пример с более глубоким примером, с которым вы можете играть на jsfiddle .
// How to force async functions to execute sequentially
// by using deferred pipe chaining.
// The master deferred.
var dfd = $.Deferred(), // Master deferred
dfdNext = dfd; // Next deferred in the chain
x = 0, // Loop index
values = [],
// Simulates $.ajax, but with predictable behaviour.
// You only need to understand that higher 'value' param
// will finish earlier.
simulateAjax = function (value) {
var dfdAjax = $.Deferred();
setTimeout(
function () {
dfdAjax.resolve(value);
},
1000 - (value * 100)
);
return dfdAjax.promise();
},
// This would be a user function that makes an ajax request.
// In normal code you'd be using $.ajax instead of simulateAjax.
requestAjax = function (value) {
return simulateAjax(value);
};
// Start the pipe chain. You should be able to do
// this anywhere in the program, even
// at the end,and it should still give the same results.
dfd.resolve();
// Deferred pipe chaining.
// What you want to note here is that an new
// ajax call will not start until the previous
// ajax call is completely finished.
for (x = 1; x <= 4; x++) {
values.push(x);
dfdNext = dfdNext.pipe(function () {
var value = values.shift();
return requestAjax(value).
done(function(response) {
// Process the response here.
});
});
}
Некоторые люди отмечают, что понятия не имеют, что делает код. Чтобы понять это, сначала нужно понять обещания JavaScript. Я почти уверен, что обещания скоро станут нативной функцией языка javascript, так что это должно дать вам хороший стимул для изучения.