我正在 nodejs 模块中执行数据库连接。但是它的回调没有被调用。
这是我的模块-
*getChapterList.js
var mysql=require('mysql');
var client=mysql.createClient({
user:'mysql',
password:''
});
client.useDatabase('test');
module.exports.get_chapter_list = function(subject_id){
client.query("select distinct chapter_id from course_associations where subject_id="+subject_id+" and status_id=1",
function(err,results,fields){
return results;
});
return "hello";
};
现在我称这个模块为-
rs=require('./getChapterList');
rs.get_chapter_list(1);
// Output: hello
但预期的 o/p 是结果数组。
谷歌了很多。但没有结果..
最佳答案
回调将在查询完成后调用,结果的返回值将传递回创建回调的方法,然后丢弃它。
输出为“hello”的原因是 get_chapter_list
函数返回的内容。
发生的事情是:
- 您调用
get_chapter_list
函数 client.query
触发对数据库的请求client.query
函数返回。get_chapter_list
函数返回“hello”。- SQL查询完成并调用回调
- 您的回调方法被调用但什么也不做(它只返回结果,但该返回值被返回给回调的调用者(
client.query
中的某处),后者将其丢弃)。
要得到你想要的东西,你可能需要异步思考。
定义方法为
module.exports.get_chapter_list = function(subject_id, callback){
client.query("select distinct chapter_id from course_associations where subject_id="+subject_id+" and status_id=1",
function(err,results,fields){
// doesn't contain any error handling
callback(results);
});
};
然后调用方法:
rs.get_chapter_list(1, function(results) {
console.log(results); // or whatever you need to do with the results
});
关于node.js - nodejs-模块中的回调不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12054921/