Get values from within a function that is inside another function

4

I'm developing a small Javascript application that makes use of Web SQL. I want to create a function that returns the value of a variable from the VARIABLES table, as well as its observation. It would be something like this:

valor = pegaVariavel("nome da variavel");

Unfortunately I can not do this. The code I'm using for this is:

function pegaVariavel(variavel, obs) {
    var valores = { observacao: '', valor: ''};
    html5sql.process([{
        "sql" : "SELECT valor, obs FROM variaveis WHERE variavel=?",
        "data" : [variavel],
        "success": function() {}
    }],
    dbSuccess,
    function(e) { console.log("Erro ao recuperar variavel do banco: "+ e.message) });

    function dbSuccess(t, r) {

        console.log("Valor da Variavel "+variavel+" resgatado do banco com sucesso.");
        valores.observacao = r.rows.item(0)[['obs']];
        valores.valor = r.rows.item(0)[['valor']];
    }

    if (obs == 1) {
        console.log('Observação da variavel '+variavel+': '+r.rows.item(0)[['obs']]);
    }
    if (obs == 2) {
        return valores.observacao;
    }
    if (typeof obs == 'undefined') {
        return valores.valor;
    }
}
I'm using the html5sql library to work with the bank , # "> HTML5SQL.JS

How can I resolve this?

    
asked by anonymous 06.07.2014 / 17:39

2 answers

2

It will not work that way, because the operation to get the data is asynchronous. It only completes after that the pegaVariavel function returns. What you can do is pass a callback to the function, and use the data just inside the callback:

function pegaVariavel(variavel, obs, dbSuccess) {
    var valores = { observacao: '', valor: ''};
    html5sql.process([{
        "sql" : "SELECT valor, obs FROM variaveis WHERE variavel=?",
        "data" : [variavel],
        "success": function() {}
    }],
    dbSuccess,
    function(e) { console.log("Erro ao recuperar variavel do banco: "+ e.message) });
}

pegaVariavel('variavel', '', function(t, r){
    console.log("Valor da Variavel resgatado do banco com sucesso.");
    console.dir(valores);
    // Use os valores aqui dentro
});
    
07.07.2014 / 03:56
1

The variable valores has to be defined with a global scope , ie outside of any function.

In this way, in any part of the document you have access to it and its values.

// Iniciar a variável globalmente
var valores = { observacao: '', valor: ''};

function pegaVariavel(variavel, obs) {
  // variável "valores" está disponivel dentro deste scope
}

function dbSuccess(t, r) {
  // variável "valores" está disponivel dentro deste scope
}

// variável "valores" está disponivel aqui

As you were defining the variable valores within the function pegaVariavel() only inside it you had access to the variable because its scope was limited to the function where it was defined.

You can read more about this: MDN - var < sup> (English)

    
06.07.2014 / 22:15