Создайте массив функций для выполнения, поместите каждую функцию в массив, если запрос еще не завершен, затем выполните цикл по массиву, выполняющему функции, когда запрос AJAX завершится.
Например:
var functionQueue = [];
function exec(func) {
if (functionQueue)
functionQueue.push(func);
else //AJAX request already finished
func();
}
$.ajax({
...
success: function(...) {
...
var queue = functionQueue;
functionQueue = false; //Prevent re-entrancy
for (var i = 0; i < queue.length; i++)
queue[i]();
}
});
РЕДАКТИРОВАТЬ : Демо
2 и РЕДАКТИРОВАТЬ : Для использования exec
внутри объекта может быть полезно сохранить this
:
var functionQueue = [];
function exec(func, context) {
if (functionQueue){
functionQueue.push(function() { func.call(context); });
} else {
func.call(context);
}
}
var hello = {
say: function(txt){
exec(function() {
alert(txt); //this still works
}, this);
},
auth: function(){
$.get("/echo/json/", function(resp){
var queue = functionQueue;
functionQueue = false; //Prevent re-entrancy
for (var i = 0; i < queue.length; i++){
queue[i]();
}
});
}
};
hello.say("hello world!");
hello.auth();
Возможно, вы захотите поместить очередь в ваш объект:
var hello = {
functionQueue: [],
exec: function(func) {
if (this.functionQueue){
this.functionQueue.push(func);
} else {
func.call(this);
}
},
say: function(txt){
this.exec(function() {
alert(txt); //this still works
});
},
auth: function(){
var me = this;
$.get("/echo/json/", function(resp){
alert('AJAX finished!');
var queue = me.functionQueue;
functionQueue = false; //Prevent re-entrancy
for (var i = 0; i < queue.length; i++){
queue[i].call(me);
}
});
}
};
hello.say("hello world!");
hello.auth();