如何在另一个模块中使用一个模块函数的输出

How to use the output from a function of a module in another module

本文关键字:模块 一个 函数 输出 另一个      更新时间:2023-09-26

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

查询应该返回键值对中的值(hello:world)。然而,每次我试图在另一个模块中使用该变量时,我最终得到的是"true"而不是"world"。

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

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

async函数不能像sync函数那样返回值。你需要使用回调方式。像这样修改你的代码:

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