Question:
I'm developing a Javascript application and I need to make a queue of ajax requests, and I need one after another because they manipulate some variables in my scope. jQuery.ajax
's async
parameter is deprecated, how can I make the executions run in sync
mode?
I can't post the code in full because it belongs to the company, but I can give an example.
What I have:
(function(){
var var10;
var var20;
var var30;
var var40;
function func10(){
return $.ajax({
url: '/path/to/file',
success: function(data){
/* Faça algo */
var10 = data.algumacoisa;
}
})
}
function func20(p){
return $.ajax({
url: '/path/to/file',
data: {'algumacoisa': p},
success: function(data){
/* Faça algo */
var20 = data.algumacoisa;
}
})
}
function func30(p){
return $.ajax({
url: '/path/to/file',
data: {'algumacoisa': p},
success: function(data){
/* Faça algo */
var30 = data.algumacoisa;
}
})
}
function func40(p){
return $.ajax({
url: '/path/to/file',
data: {'algumacoisa': p},
success: function(data){
/* Faça algo */
var40 = data.algumacoisa;
}
})
}
})();
What I want:
I need all the functions are executed in the order func10().func20(var10).func30(var20).func40(var30)
and also to compliance with success
, ie after each success
run the next function. I'm not sure the $.when
method does this, as the functions cannot be run in parallel.
What I don't want:
I don't want to have to call each function on the success
of the previous one:
function func2(p){
return $.ajax({
url: '/path/to/file',
data: {'algumacoisa': p},
success: function(data){
/* Faça algo */
var20 = data.algumacoisa;
func30(var20);
}
})
}
Because if I need to put another call in the middle of the queue, I don't want to go digging through the code and have to keep changing all the flames, I just want to mess with the queue, for example:
func10().func15(var10).func20(var15).func30(var20).func40(var30)
Is it possible to do that? If yes, what is the best way? If not, why?
Answer:
You can have an array with the list of functions you want to run and run/empty the list as a callback.
The idea would be:
var funcArray = [function (data) {
/* Faça algo */
return data.algumacoisa;
}, function (data) {
/* Faça algo */
return data.algumacoisa;
}, function (data) {
/* Faça algo */
return data.algumacoisa;
}, function (data) {
/* Faça algo */
return data.algumacoisa;
}];
function tratadorAJAX(dataAnterior, next){
if (!next) return;
$.ajax({
url: '/path/to/file',
data: {'dataAnterior': dataAnterior},
success: function(data){
var proximaData = next(data);
tratadorAJAX(proximaData, funcArray.pop());
}
})
}
tratadorAJAX(dataInicial, funcArray.pop());