如何使用另一个模块中模块功能的输出

时间:2013-01-20 12:39:45

标签: javascript node.js redis

我有一个mdoule,我创建了一个数据库连接和一个运行查询的函数。 我想在另一个模块中使用此查询的输出。我该怎么做?

该查询应该从键值对(hello:world)返回值。 但是,每当我尝试在另一个模块中使用变量时,我最终都会使用“true”而不是“world”。

我的代码在这里 https://github.com/rishavs/RedisDbConnect

我想从app.js调用getValue函数,也可能调用console.log(db.getValue())输出。

1 个答案:

答案 0 :(得分:1)

您无法从同步等异步函数返回值。你需要使用回调方式。像这样修改你的代码:

getValue函数:

var getValue = function(cb) {
    dbConnection.get("hello", function (err, reply) {
        var val = reply ? reply.toString() : null;
        cb(err, val);
    });
};

控制器:

app.get('/json', function(req, res, next) {
    res.contentType('application/json');
    db.getValue(function(err, val) {
        if (err) return next(err);
        res.send(val);  
    });
});