Access variable from within function: scope problem?

Asked

Viewed 196 times

2

How do I access the variable dados from within the 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 in the console. I believe it is 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?

1 answer

5


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

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 logic of data processing. Thus:

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

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

You can even simplify:

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

function trataDados(dados) {
    // faz o que for necessário
}
  • Thanks, buddy! That’s right!

Browser other questions tagged

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