使用process.nextTick进行节点mysql查询

时间:2014-12-29 10:00:06

标签: node.js node-mysql

这是我的简化问题:

我想将我的数据库功能分离到另一个文件。它不起作用(我必须使用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

这是db文件:

// 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;

我该如何解决这个问题?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

这根本不起作用(可能根本不起作用)。 db.selectUserByEmail('levon')很可能是异步的,也可能会返回undefined,因此您会收到Cannot read property 'length' of undefined错误并不奇怪。

问题是,为什么不在第一种情况下得到它?这很简单:你(再次,可能)在try..catch区块内。有些框架将代码包装在这些框架中,但process.nextTick调用稍后提供了函数,因此try..catch无效。