Using Promises and Deffered in everyday life

Asked

Viewed 102 times

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!!!!

1 answer

0

Hello. If the calls are very similar you can do something like this:

var url = '/echo/json/';
var acao = 'CarregaDadosCliente';
var dados = {acao: acao,codigo: null};

function funcao1(json,nom_cod){
    dados.codigo = typeof nom_cod === 'undefined' ? '' : json[nom_cod];

    $.post(url, dados, function(json){
        return json;
    }).fail(function() {
        alert("deu erro");
    });
}


alert(funcao1(funcao1(funcao1(),'cod_cliente'),'cod_pedido'));

You can even add the url and action as a parameter if they are different. Follows link.

Another idea would be to create a function that takes an array of objects like:

[{url:'url1',acao:'acao1',cb:funcao2},{url:'url2',acao:'acao2',cb:funcao3}]

This function would be recursive and takes an item from the array at each call end.

I never had to use Promises (just out of curiosity) I used this link http://www.html5rocks.com/en/tutorials/es6/promises/? redirect_from_locale=en

In the "Error Handling" section there is a very good example of asynchronous nested calls. See if it helps.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.