Access variable from within function: scope problem?

1

How do I access the dados variable from within function ? Example below:

     var dados; 

     PagSeguroDirectPayment.getBrand({

            cardBin: this.pedidoSoft.numCard,
            success: function(response) {

                 dados = response;
            },
            error: function(response) {},
            complete: function(response) {}
    });

    console.log(dados);

This code is printing undefined on the console. I believe it's a variable scope problem. The variable being accessed inside is not the same as outside. How can I access this variable from within the function?

    
asked by anonymous 07.07.2017 / 03:23

1 answer

4

It is not a scope problem. The problem is that the function is asynchronous, it's a callback . Then you assign response to dados , but only after console.log has already rolled.

Whatever you need to do with the data, do it within the successful callback. The cleanest way is to call a function and pass the data to it. This even encapsulates the data handling logic. So:

// ...
    success: function(response) {
        trataDados(response);
    },
// ...
});

function trataDados(dados) {
    // faz o que for necessário
}

It's even simplified:

// ...
    success: trataDados,
    error: function(response) {},
    complete: function(response) {}
});

function trataDados(dados) {
    // faz o que for necessário
}
    
07.07.2017 / 03:32