2
I’m studying about these items and I’m having doubts about how to apply them to my projects. I currently use callback for everything but the structure of the code is tense.. and on the Internet I found many articles talking about Promises and Deffered.. but I could not understand how this would be in practice..
If not to abuse, but already abusing, I would like to understand how would be the following situation, I have 3 functions and each one has a callback, so the function 2 is only called when function 1 ends and returns me the callback of your data, so function 2 executes and then calls function 3, and in this way successively for more functions if it had.
Then my code would look like this (this code is an example only)
function funcao1(callback){
$.ajax({
type: "POST",
url: minhaUrlPost,
data: {
acao: 'CarregaDadosCliente',
codigo: codigo
},
dataType: "json",
success: function (json){
return callback(json);
},error: function (){
alert("deu erro")
}
});
}
function funcao2(cod_cliente,callback){
$.ajax({
type: "POST",
url: minhaUrlPost,
data: {
acao: 'CarregaPedidosCliente',
codigo: cod_cliente
},
dataType: "json",
success: function (json){
return callback(json);
},error: function (){
alert("deu erro")
}
});
}
function funcao3(cod_pedido,callback){
$.ajax({
type: "POST",
url: minhaUrlPost,
data: {
acao: 'CarregaItensPedidoCliente',
codigo: cod_pedido
},
dataType: "json",
success: function (json){
return callback(json);
},error: function (){
alert("deu erro")
}
});
}
funcao1(function(json){
funcao2(json.cod_cliente, function(json){
funcao3(json.cod_pedido, function(json){
//faz alguma coisa ou chamaria mais functions...
});
});
});
The above example works... but I know that it can improve both this structure and the working method used. and would like the help of the community to be able to better understand this in the practice of the above example.
Thank you in advance!!!!