NodeJs return function - Mysql query

0

I am not able to return value in the function, I know it is wrong, but I have tried several times without success. The query is being performed and brings the password, the problem is to return this value to whoever ran the function:

function obtemSenha() {
    var read_R = 'select * from senha';
    var ret = 0;
    connect.getConnection(function(err, connection){
      connection.query(read_R, function(err, data, fields){
        if(err) throw err;
        else {
            console.log('SenhaREC....0: ${data[0].senha}');
            ret = data[0].senha;
            connection.release();
        }
      });
   });
   return ret;
};

var senha = obtemSenha();
    
asked by anonymous 11.11.2018 / 18:02

1 answer

3

I have never worked with Node.js + MySQL, but judging that IO operations on Node.js are asynchronous, I imagine that return will not work, since you are trying to return a variable before it receives the value of database. Try using a promise :

function obtemSenha() {
    return new Promise((resolve, reject) => {
        var read_R = 'select * from senha';
        var ret = 0;
        connect.getConnection(function(err, connection) {
            connection.query(read_R, function(err, data, fields) {
                if(err) reject(err);                
                console.log('SenhaREC....0: ${data[0].senha}');
                connection.release();
                resolve(data[0].senha);
            });
        });
    });
}

async function foo() {
    try {
        var senha = await obtemSenha();
    } catch (err) {
        console.error('Erro', err);
    }
}
    
11.11.2018 / 18:29