Get values from within a function that is within another function

Asked

Viewed 2,474 times

4

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

valor = pegaVariavel("nome da variavel");

Unfortunately I’m not able to do that. 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;
    }
}

Obs: I am using html5sql library to work with the database, HTML5SQL.JS

How can I fix this?

2 answers

2

It will not work that way, because the operation of collecting the data is asynchronous. It is only completed afterward that the function pegaVariavel returns. What you can do is pass a callback to the function, and use the data only 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
});

1

The variable valores has to be defined with a Scope overall, that is, outside any function.

That 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

How you were setting the variable valores within the function pegaVariavel() only within it did you have access to the variable because its Scope was limited to the function where it was defined.

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

Browser other questions tagged

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