Nodejs return function - Mysql query

Asked

Viewed 461 times

0

I’m not able to return value in function, I know it’s wrong, but I’ve made several unsuccessful attempts. The query is being performed and brings the password, the problem is to return this value to whoever executed 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();

1 answer

3


I’ve never worked with Node.js+Mysql, but judging that IO operations on Node.js are asynchronous, I imagine the return will not work as you are trying to return a variable before it receives the value from the 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);
    }
}
  • It worked!!! Thanks!!!

Browser other questions tagged

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