How to obtain the value of the variable outside the function?

Asked

Viewed 42 times

0

How to get the value of var DI out of office? I’m a rookie, and I curled up..

I need to include it in another function but I can’t get the value out of it :(

$(document).ready(function () {
  $.ajax({
    url: "https://www2.cetip.com.br/ConsultarTaxaDi/ConsultarTaxaDICetip.aspx"
  }).then(function (respomse) {
    var data = JSON.parse(respomse);
    $('#taxaPct').text(data.taxa + '%');
    DI = data.taxa; 
    console.log(DI); <---- Aqui ele exibe no console
  });
});

console.log(DI); <---- Quero acessar ela fora da função

2 answers

-1

This type of doubt is very common in beginners. To be able to access the variable DI out of these callback functions, you can do two things:

  • Or you use Promises:
const Promise = new Promise((resolve) => {
  $(document).ready(function () {
    $.ajax({
      url: "https://www2.cetip.com.br/ConsultarTaxaDi/ConsultarTaxaDICetip.aspx"
    })
      .then(function (respomse) {
        var data = JSON.parse(respomse);
        $('#taxaPct').text(data.taxa + '%');
        const DI = data.taxa; // O `const` é uma forma de criares variáveis "imutáveis" no EcmaScript 6.
        resolve(DI);
        console.log(DI);
      });
  });
});

Promise
  .then(DI => console.log(DI)); // Isto é uma arrow function, mas podes utilizar funções anónimas convencionais.

  • Or use the good old-fashioned callbacks:
function consultarTaxaDi(callback) {
  $(document).ready(function () {
    $.ajax({
      url: "https://www2.cetip.com.br/ConsultarTaxaDi/ConsultarTaxaDICetip.aspx"
    }).then(function (respomse) {
      var data = JSON.parse(respomse);
      $('#taxaPct').text(data.taxa + '%');
      const DI = data.taxa; 
      console.log(DI);
      callback(DI);
    });
  });
}

consultarTaxaDi(function(DI) {console.log(DI)}); Podes também usar arrow functions.

Although these examples work well I, in your side, would process this variable DI within the function where this is declared.

-1


whereas is just trying to access a variable outside the scope or is facing an asynchronous request problem:

Access out of scope:

If you are trying to access a variable that is outside the scope of the function where you want it, you can declare it in a scope to which both functions have access, as in the example:

var DI = ''; // inicializando com um valor vazio, para que não ocorra um acesso a uma variável não inicializada
$(document).ready(...

And you can still use the value of the same variable in another function after having populated it.

Asynchronous request:

If the problem is accessing the variable outside the scope of the request because it has no value (but had already been declared in an external scope), you can make a synchronous request as follows on jQuery:

  $.ajax({
    url: "https://www2.cetip.com.br/ConsultarTaxaDi/ConsultarTaxaDICetip.aspx",
    async: false // fazendo com que a requisição seja síncrona; Não haverá execução até que o processo dessa função termine.
  }).done(function (response) {
    var data = JSON.parse(response);
    $('#taxaPct').text(data.taxa + '%');
    DI = data.taxa;
  });

Note that I am not using then and yes done, given that then returns a new Promise (would continue to be treated later, asynchronously). By making nothing else happen until the request is completed, you should be able to popular the variable the way you need it. This is because the requisition is occurring in another "process", while its main code continues running. So when arriving at the use of its variable DI, it has not yet been populated, ie the request has not yet received a response.

Another detail that can lead to problems is the fact of having the call inside the [$(document).ready], because it may be that the function that makes use of its variable DI has already been called but the page has not yet fully loaded. The function will only be called on full charge of GIFT.

That being said, I recommend that you review the code to avoid synchronous calls when possible, as all the code will wait for the call to finish to continue and this is bad for the user experience, giving the impression that something "stuck". You should see a message like the one below in your browser console when using calls like:

[Deprecation] Synchronous Xmlhttprequest on the main thread is deprecated because of its detrimental effects to the end user’s Experience. For more help, check https://xhr.spec.whatwg.org/.

Browser other questions tagged

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