node.js - nodejs-模块中的回调不起作用

标签 node.js

我正在 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 函数返回的内容。

发生的事情是:

  1. 您调用get_chapter_list 函数
  2. client.query 触发对数据库的请求
  3. client.query 函数返回。
  4. get_chapter_list 函数返回“hello”。
  5. SQL查询完成并调用回调
  6. 您的回调方法被调用但什么也不做(它只返回结果,但该返回值被返回给回调的调用者(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/

相关文章:

node.js - 我可以使用 MongoDB 模式模型来定义 IndexedDB 索引吗?

jquery - 前端 jQuery 代码无法使用 Node.js 正确执行

javascript - 下面的代码将向控制台输出什么?原因是什么?

node.js - Node - 检查目录是否存在

node.js - 聚合组上的 Mongoose 错误

javascript - 运行discord bot时出现错误代码(JS)

node.js - 运行测试时“描述未定义”

node.js 挂起我的 Mac 上的其他程序

c++ - 如何从 Node native 插件正确创建 Buffer 对象?

javascript - gulp - 我必须为每个项目安装插件吗?