Javascript return function

Asked

Viewed 50 times

1

var pegaNomeMedico = {
    nome : function(){          
        banco.transaction(function(tx){         
            tx.executeSql(sqlMedicos.selecionaTodosOsMedicosSemFiltros, [], function(tx, resposta){
                var linha = resposta.rows.length;
                 return resposta.rows.item(0).nome_medico;              
            })
        })
    }
}

alert(pegaNomeMedico.nome());

She’s just returning Undefined me

I’d like to know why ?

If I put one alert(resposta.rows.item(0).nome_medico) works normal more in Return not this coming doctor’s name

  • It seems that this function is asynchronous. How is calling it? pegaNomeMedico.nome()?

1 answer

1

You can’t do it that way. The database.transaction function is probably asynchronous and remote more than js runtime to answer.

Do so:

var pegaNomeMedico = {
    nome : function(callback){          
        banco.transaction(function(tx){         
            tx.executeSql (sqlMedicos.selecionaTodosOsMedicosSemFiltros, [], function(tx, resposta){
                 var resp = resposta.rows.item(0).nome_medico;
                 If (typeof callback == "function")
                     callback(resp);
            })
        })
    }
}

pegaNomeMedico.nome(function(resposta){
    alert(resposta);
});

EDIT

At the user’s request in the comments:

var pegaNomeMedico = {
    nome: null,
    pegaNome: function(){
        return this.nome;
    },
    pegaNomeServidor : function(callback){          
        banco.transaction(function(tx){         
            tx.executeSql (sqlMedicos.selecionaTodosOsMedicosSemFiltros, [], function(tx, resposta){
                 var resp = resposta.rows.item(0).nome_medico;
                 pegaNomeMedico.nome = resp;
                 if (typeof callback == "function")
                     callback(resp);
            })
        })
    }
}

You continue using the function directly like this:

pegaNomeMedico.pegaNomeServidor(function(resposta){
    alert(resposta);
});

However, there is also the possibility of:

pegaNomeMedico.pegaNome();

Note that in order to use stickName() you will need to understand that if called before return from stickNew(), you will get as a response null. This is unavoidable, because it is the execution time of the JS query x execution time, which are not simultaneous.

  • great, more how do I call Return. type like this

  • what would it be like to call Return somewhere other than in Alert? Kind like this stickNomeMedic.name();

  • It is impossible to do the way you want with an asynchronous type function. I will edit the question with another scenario.

  • It didn’t work out, Bruno. Keep giving Null

Browser other questions tagged

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