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

时间:2012-08-21 12:32:52

标签: 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是结果数组。

googled alot.but no result ..

3 个答案:

答案 0 :(得分:3)

您需要异步返回结果:

exports.get_chapter_list = function(subject_id, callback) {
    client.query("select ...", callback);
};

...

var rs = require('./getChapterList');

rs.get_chapter_list(1, function(err, results) {
    if (err) {
        // handle error
    } else {
        // do something with results
        console.log(results);
    }
});

答案 1 :(得分:3)

在查询完成后将调用回调函数,结果的返回值将传递回创建回调的方法,然后将其丢弃。

输出为“hello”的原因是因为get_chapter_list函数返回的原因。

会发生什么:

  1. 您拨打get_chapter_list功能
  2. client.query会触发对数据库的请求
  3. client.query函数返回。
  4. get_chapter_list函数返回“hello”。
  5. SQL查询完成并调用回调
  6. 您的回调方法被调用并且什么都不做(它只返回结果,但是返回值被传递回回调的调用者(client.query内的某个地方),丢弃它)。
  7. 为了获得你想要的东西,你可能需要异步思考。

    将方法定义为

    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
    });
    

答案 2 :(得分:0)

scttnlsn的回答是正确的,因为我遇到了这个问题并且只是通过将回调函数作为参数传递来解决。

尝试:

var mysql=require('mysql');
var client=mysql.createClient({
  user:'mysql',
  password:''
});
client.useDatabase('test');
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){
                callback( results );
});
return "hello";
};

然后

var rs = require('./getChapterList');

rs.get_chapter_list(1, function(results) {
  console.log(results);
}
});

这将打印欲望输出。