$. getJSON does not record return on variables

Asked

Viewed 754 times

6

I created a function that takes the values of a JSON and (should send these values to variables within the function) so I could use these variables in the function continuation. The problem is that when I run the function it does not return the values... if I take the internal code of the same and run in the DOM it works but calling it does not... Somebody give me a hand please?

    //get connection info's to access the system
    function connection(){

      //vars
      var servername;
      var database;
      var username;
      var password;

      //get JSON values
      $.getJSON('./data/configuration.json',function(data){
        servername = data.servername;
        database = data.database;
        username = data.username;
        password = data.password;
      });

      console.log(servername);
      console.log(database);
      console.log(username);
      console.log(password);
    }

1 answer

10


The problem is that the getJSON is an operation asynchronous, which means that it is not completed immediately. The code that comes after the getJSON (which includes your console.log and the return of connection) runs before JSON arrives.

So you pass a function as a second parameter, as it is guaranteed that it will only run when the data is available.

That is, you can only use the data after receiving it. I suggest dividing your code into smaller functions, and calling the function responsible for handling the data when it is available.

For example:

//get connection info's to access the system
function connection(){
  //get JSON values
  $.getJSON('./data/configuration.json',function(data){
    usaDados(data);
  });
}

function usaDados(dados) {
  console.log(dados.servername);
  console.log(dados.database);
  console.log(dados.username);
  console.log(dados.password);
}

You can also change the outermost function to receive a callback:

//get connection info's to access the system
function connection(callback){
  //get JSON values
  $.getJSON('./data/configuration.json', callback);
}

function usaDados(dados) {
  console.log(dados.servername);
  console.log(dados.database);
  console.log(dados.username);
  console.log(dados.password);
}

// LEIA: assim que obtiver a conexão, usa os dados
connection(usaDados);

Browser other questions tagged

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