Store a variable to use outside of Function

Asked

Viewed 82 times

0

wrote the following code

app.post("/Dialogflow", function(request, response) { 
  
  var connection = mysql.createConnection({ 
    host: process.env.MYSQL_HOST, 
    user: process.env.MYSQL_USER, 
    password: process.env.MYSQL_PASS, 
    database: process.env.MYSQL_DB 
  }); 
  connection.connect();
  
  var intentName = request.body.queryResult.intent.displayName;

  else if(intentName == 'psqcont'){ 
    console.log('Pesquisar Contato');
    var TelefoneContato = request.body.queryResult.parameters['Celular'];
    var query = 'select * from Clientes where Celular = "'+TelefoneContato+'"';
    connection.query(query, function (error, results, fields) {
    var Endereco = results[0].endereco
      try{
            if (error) throw error;
            connection.end();
            if(TelefoneContato == results[0].Celular){
        var contato = ''; contato = '‍♂️Ola '+results[0].Nome+"\n"
          +'Digite *1* para pedir no restaurante ️'+'\n'
          +'Ou *2* para pedidos na loja ';
        response.json({"fulfillmentText": contato })
      }
      
      else{
        if (error) throw error;
        connection.end();
        var tchauresp = ''; tchauresp = 'Não achamos seu cadastro!';
        response.json({"fulfillmentText": tchauresp})
      }}
      catch(e){
        var tchauresp = ''; tchauresp = '‍♂️Opa! Vimos que seu numero não está cadastrado'
          +"\n"+
          'Por favor digite *3* para realizar o cadastro';
        response.json({"fulfillmentText": tchauresp})
        
      }
    });
  }
  
  else if(intentName == 'psqcont - 1 rest'){
    response.json({"fulfillmentText":'Para entrega, digite *1*, e para retirada digite *2*'})
    }
  
  else if(intentName == 'psqcont - 1 entrega'){
    console.log('Pesquisar Endereço');
      var respEnd = '', respEnd = "Confira se o endereço abaixo será o mesmo da entrega:"+
                                "Endereço: "+Endereco+
                                "Complemento: "
    response.json({"fulfillmentText": respEnd })
  

    }
  
 }
);

I’m having trouble using the var Endereco of else if(intentName == 'psqcont') within the else if(intentName == 'psqcont - 1 entrega') I’ve tried Return I tried to turn var Endereco into global, but I was not successful if anyone knows a way to make var address go global or if someone can point out my mistake would help a lot.

  • to declare a global variable, if I’m not mistaken, you don’t need to use var. just use address = true; instead of var address = true;

2 answers

0


For you to use a variable value of a function outside of it, you need to return a value using:

function MyFunction(){
 var Endereco = true; 
 return Endereco; //essa variavel estará disponivel fora dessa função.
}

To access this variable outside of it, do the following:

function NovaFunction (){

 var teste = MyFunction(); // onde MyFunction() trará o valor de retorno.
 alert(teste); // true
}
  • In function NovaFunction() is giving 'MyFunction' is not defined

  • @Joabeferri this code here works smoothly. Anyway try declaring Addressglobally, without var and test again. But it should work smoothly.

0

function myFunction () {
    function exp(){
            endereco = true 
            return endereco 
    }
    exp()
    return endereco
}

if you make a function that returns only this variable and then call, it is in global scope , so call the function

more optimized this code would look like this:

(function myFunction () {
            endereco = true 
})()

console.log(endereco)

console-less.

Browser other questions tagged

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