0

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.

Kaya Toast
  • 5,267
  • 8
  • 35
  • 59

1 Answers1

0

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.

vkurchatkin
  • 13,364
  • 2
  • 47
  • 55
  • You are right ... the first case also works intermittently; I'll modify my question; must be because of the asynchronous nature. All I was trying was to separate all the mysql queries/functions to a different file. Any suggestions please ? – Kaya Toast Dec 29 '14 at 12:33
  • That is a basic `return from asynchronous function` issue. Check this: http://stackoverflow.com/questions/18950984/return-value-from-asynchronous-function-in-nodejs – vkurchatkin Dec 29 '14 at 12:57