How to return async data from a mysql query in a function using node.js?


I am Node.js beginner coming from a PHP background.
I am using mysql, module node-mysql (Github: felixge/node-mysql) and unfortunately it is async.
The debug line "__2" came before "__1", so the function returns before the query occurs.
What should I do ?

var db = require('../classes/db.js')
var method = Usuario.prototype;

function Usuario() {
    // constructor
}

method.doAuth = function(usuario, senha) {
    var retorno = 0
    var sql = 'SELECT * from `tb_usuario` WHERE `usuario` = ? and `senha` = ?'
    db.query(sql, [usuario, senha], function(err, rows, fields) {
    if (err) throw err
    console.log("__1")
    if(rows.length > 0)
        retorno = rows[0].id        
    })
    console.log("__2")
    return retorno
}

module.exports = Usuario

You will just have to embrace this as part of node. You can handle it with a variety of different paradigms. The simplest would be node's preferred CPS:

method.doAuth(usuario, senha, callback) {
    db.query(query, functoin (err, rows, fields) {
        callback(err, fields);
    });
};

Then you would call it like:

lib.doAuth("key", "value", function (err, fields) {
    if (err) throw err;
    // do stuff with the rows
});

  1. Add a parameter to your function called callback - this is your callback function: method.doAuth = function(usuario, senha, callback) {
  2. inside your query callback, return the callback with an error object and the result: db.query(sql, [usuario, senha], function(err, rows, fields) { .... if(rows.length > 0) retorno.id_usuario = rows[0].id; return callback(error, usuario);
    });
  3. call your function with a callback parameter:
    doAuth(usuario, senha, function(error, result) { //handle error and result });

deasync is what you are looking for. This will get your desired result:

method.doAuth = function(usuario, senha) {
    var retorno = 0
    var sql = 'SELECT * from `tb_usuario` WHERE `usuario` = ? and `senha` = ?'

    var rows
    try{
      rows = require('deasync')(db.query)(sql, [usuario, senha])
    }
    catch(err) throw err
    console.log("__1")
    if(rows.length > 0)
        retorno = rows[0].id        
    })
    console.log("__2")
    return retorno
}