Search code examples
node.jsnode-mysql

node mysql query with process.nextTick


Here is my simplified problem:

I want to separate out my database functions to a different file. It is not working (I have to use process.nextTick())

var db = require('./db/db_functions');

process.nextTick(function() {
    var rows = db.selectUserByEmail('levon');
    if (rows.length) { ... }
});

// TypeError: Cannot read property 'length' of undefined
//    at /Users/Test/app.js:38:13
//    at process._tickCallback (node.js:442:13)
//    at Function.Module.runMain (module.js:499:11)
//    at startup (node.js:119:16)
//    at node.js:929:3

and here is the db file:

// db_functions
function selectUserByEmail (email){
    client.query("select * from users where email = ?", email, function(err,rows){
        if(err) { throw err; }
        return rows;
    });
}
module.exports.selectUserByEmail = selectUserByEmail;

How can I solve this ? Thanks for your help.


Solution

  • This shouldn't work (and probably is not working) at all. db.selectUserByEmail('levon') is most likely asynchronous and, also likely, returns undefined, so it's not surprising that you get Cannot read property 'length' of undefined error.

    The question is, why don't you get it in the first case? It's really simple: you are (again, likely) inside a try..catch block. Some frameworks wrap your code in these, but process.nextTick calls provided function later, so try..catch has no effect.