JavaScript function return

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());

It's just returning me undefined

I wanted to know why?

If I put a alert(resposta.rows.item(0).nome_medico) it works normal but no return is not coming the name of the doctor

    
asked by anonymous 08.09.2017 / 14:33

1 answer

1

You can not do it that way. The bank.transaction function is probably asynchronous and remote more than the js execution time to respond.

Do this:

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

Upon user request in 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 to use the function directly like this:

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

However, there is also the possibility of doing so:

pegaNomeMedico.pegaNome();

Note that in order to use nameName () you will have to understand that if you call before the return of the ServerName (), you will get null response. This is inescapable because it is the execution time of the query x runtime of the JS, which are not concurrent.

    
08.09.2017 / 14:43