$ .getJSON does not write return on variables

6

I created a function that takes the values of a JSON and (should send those values to variables inside the function) so I could use these variables in the continuation of the function. The problem is that when I run the function it does not return the values ... if I take the internal code from it and run it on the DOM it works but calling it does not ... Does anyone give me a help 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);
    }
    
asked by anonymous 12.09.2014 / 20:12

1 answer

10

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

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

That is: you can only use the data after receiving them. I suggest dividing your code into smaller functions, and calling the function responsible for handling the data when they are 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);
    
12.09.2014 / 20:16