0


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
G4BB3R
  • 196
  • 2
  • 11
  • 1
    `doAuth` must itself follow the asynchronous paradigm - e.g. use a callback (or promise) to resume execution of the next action. In general one can't "switch back" arbitrarily. – user2864740 Aug 22 '14 at 20:35
  • Can you give me an example, please ? – G4BB3R Aug 22 '14 at 20:37
  • It is the same issue, with [some of] the same solutions, as discussed in http://stackoverflow.com/a/14220323/2864740 (just within context of Node; I am a fan of Promises/A vs. ad hoc callbacks.) – user2864740 Aug 22 '14 at 20:39
  • For Promises (which I again recommend), see http://stackoverflow.com/questions/4296505/understanding-promises-in-node-js , http://howtonode.org/promises , http://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/ , etc. – user2864740 Aug 22 '14 at 20:43
  • Also related - http://stackoverflow.com/questions/9935920/how-to-write-a-node-js-function-that-waits-for-an-event-to-fire-before-returnin?lq=1 , http://stackoverflow.com/questions/21819858/how-to-wrap-async-function-calls-into-a-sync-function-in-node-js-or-javascript?rq=1 – user2864740 Aug 22 '14 at 20:44

3 Answers3

1
  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 });
Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159
  • After everything I've read about callbacks for whatever reason this made a lot more sense and it clicked. Thank you. – Jens Bodal Dec 06 '15 at 05:13
0

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
});
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
-1

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
}
abbr
  • 5,361
  • 6
  • 30
  • 44