I'm studying about these items and I'm not sure how to apply them in my projects. I currently use callback for everything but the code structure gets tense .. and on the internet I found a lot of articles talking about the Promises and Deffered .. but I could not understand how that would be in practice this ..
If you do not abuse, but already abusing, I would like to understand how the following situation would be, I have 3 functions and each one has a callback, so function 2 is only called when function 1 ends and the callback returns of your data, so function 2 executes and then calls function 3, and in this way successively for more functions if it has.
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 example above 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 better understand this in the practice of the above example.
Thanks in advance !!!!