我开始使用异步编程,我正在创建一个nodejs应用程序,我在一些文件中切片代码:index.js,ctlUser.js,DAO.js等......索引.js是主要的文件需要ctlUser和ctlUser需要DAO.js ... DAO连接数据库并执行查询......
抽象,我的结构是这样的......
Index.js
var ctlUser = require('./ctlUser.js');
var username = ctlUser.getUserName('1');
console.log("Return from ctlUser" + username);
ctlUser.js
var DAO = require('./DAO.js');
var getUserName = function(id){
var userName = DAO.executeQuery("SELECT username FROM tbUsers WHERE id = " + id );
console.log(Return from DAO = userName);
return username;
}
DAO.js在这里一切都很好......
var mysql = require('mysql');
var executeQuery = function(query) {
var connection = mysql.createConnection({
host : SERVER,
user : USER,
password : PASSWORD,
database : DATABASE
});
connection.connect();
connection.query(query, function(err, rows, fields) {
if (err) throw err;
connection.end();
console.log("Here in DAO: " + rows[0].username);
return rows[0].username;
});
};
$ node index.js
的输出是:
Return of ctlUser: undefined
Return of DAO: undefined
Here in DAO: Filipe Tagliacozzi
我抽象所有模块导出对于使用固定变量而言工作正常,但是使用数据库响应不要..如何在此结构中实现回调以将userName带到index.js?
答案 0 :(得分:8)
更改DAO.js模块中的executeQuery函数以使用回调:
var executeQuery = function(query,callback) {
var connection = mysql.createConnection({
host : SERVER,
user : USER,
password : PASSWORD,
database : DATABASE
});
connection.connect();
connection.query(query, function(err, rows, fields) {
if (err) throw err;
connection.end();
console.log("Here in DAO: " + rows[0].username);
callback(rows[0].username);
});
};
通过ctlUser.js中的getUserName函数链接回调:
var getUserName = function(id,callback){
DAO.executeQuery("SELECT username FROM tbUsers WHERE id = " + id ,function(username){
console.log("Return from DAO =" ,userName);
callback(username);
});
}
然后在index.js中使用它,如下所示:
var ctlUser = require('./ctlUser.js');
ctlUser.getUserName('1',function(username){
console.log("Return from ctlUser" + username);
});
答案 1 :(得分:-1)
它们未定义,因为您尚未导出任何内容。
节点文件在您需要时执行,但返回的是导出的内容。
在ctlUser.js中你需要导出getUserName: -
exports.getUserName = getUserName;
在DAO.js中你需要导出executeQuery: -
exports.executeQuery = executeQuery;