//dbCon.js
- var setUser = function () {
-
function callback() {
-
sql.open(conn_str, function (err, conn) {
-
if (err) {
-
console.log("Error opening the connection!");
-
return;
-
}
-
conn.queryRaw("SELECT Username,Password FROM Users", function (err, results) {
-
if (err) {
-
console.log("Error running query!");
-
return;
-
}
-
for (var i = 0; i < results.rows.length; i++) {
-
console.log(results.rows[i][0].toString());
-
}
-
return results.rows[1][0].toString();
-
});
-
});
-
}
-
return callback();
- }
- exports.setUser = setUser;
//index.js
- var users = require(‘./dbCon.js’);
- console.log(users.setUser());
// node index.js the result: return is unfined console.log is ok. 能看懂不。。。求教
11 回复
for (var i = 0; i < results.rows.length; i++) { console.log(results.rows[i][0].toString()); }
这有结果吗?
我把你的代码稍微改改,NodeJS菜鸟风格- -正好今天写完年终总结,有点时间~~ 首先是db.js:
var setUser = function (callback) {//callback回调,数据库访问是异步操作,直接return会悲剧
sql.open(conn_str, function (err, conn) {
if (err) {
console.log("Error opening the connection!");
return callback(err);
}
conn.queryRaw("SELECT Username,Password FROM Users", function (err, results) {
if (err) {
console.log("Error running query!");
return callback(err);
}
for (var i = 0; i < results.rows.length; i++) {
console.log(results.rows[i][0].toString());
}
//return results.rows[1][0].toString();//这里return的是内层函数
callback(err, results);//使用回调获取数据,第一个参数表示异常
});
});
};
exports.setUser = setUser;
index.js:
var User = require('./db.js');
User.setUser(function(err, data){
//handle err...
//handle data
});//此处传入一个函数作为回调获取结果