0

I'm currently working with chatbots and trying to work out the new await / async structure in NodeJs.

My code currently looks like this:

exports.checkUser = async function (userId, callback){
let result;
    try{
        result = await pool.query('SELECT * FROM users WHERE id = ?;', 
                [userId]);
        if(!result || result.length == 0)
        {
            return false;
        }
        else if(result.length != 0)
        {
            return true;
        }
    }
    catch(err)
    {
        console.log(err);
        callback(err, null);
    }
};

I went under the assumption I don't have to fiddle with promises while using asyc/await structure. I am calling this function somewhere else like this:

mysql.checkUser(user).then((result) =>
    {
//console for debug
      console.log(result);  
    });

Well, I know the checks for the success are pretty plain, I don't seem to get a decent result.

It's always throwing me something like inside the result object:

_callSite: Error
at Pool.query (/app/node_modules/mysql/lib/Pool.js:199:23)
at Object.exports.checkUser (/app/lib/mysql/mysql.js:49:29)
at Object.exports.checkUser (/app/lib/auth/authentication_engine.js:28:11) [...]
Veve
  • 6,643
  • 5
  • 39
  • 58
Nop0x
  • 173
  • 1
  • 14
  • 3
    Are you sure that pool.query is returning a promise/is an async function? – cassini Dec 12 '17 at 14:29
  • @cassini i was infact referring to https://stackoverflow.com/a/44004731/992238 but after rereading the whole answer and others it seems that you are right and the classical pool.query does not return a promise which can be also found in https://github.com/mysqljs/mysql/blob/master/lib/Pool.js. I might try using mysql2 next as it seems to use promises. – Nop0x Dec 12 '17 at 14:36
  • Exactly :) wrote an answer about it. – cassini Dec 12 '17 at 14:38

1 Answers1

4

pool.query is not returning a Promise, so the execution will fail when it is called as an async function. It is indeed a good idea to use mysql2 package, more on: https://www.npmjs.com/package/mysql2#using-promise-wrapper

cassini
  • 365
  • 1
  • 7
  • I got a result now finally! I'll edit my answer with my fixed code, thanks alot for helping! – Nop0x Dec 12 '17 at 14:43
  • Be careful with mysql2 if you are planning on using transactions with pool and async/await. Currently a bug exists and a fix has not been added to the package that will cause issues for you with rollbacks. Here is the link to the bug: https://github.com/sidorares/node-mysql2/issues/693. You could just use promise-mysql package which wraps node-mysql package to solve your issue. – Binary101010 Dec 24 '17 at 03:38
  • Google cloud Node examples use the promise-mysql package – nickjag Jul 17 '20 at 21:55