0

I have a mdoule, where i create a db connection and a function which runs a query. I want to use the output of this query in another module. How do I do this?

The query is supposed to return the value from the key-value pair (hello:world). However, everytime I try to use the variable in another module, I end up with "true" instead of "world".

my code is here https://github.com/rishavs/RedisDbConnect

I want to call the getValue function from app.js and maybe console.log(db.getValue()) the output.

4

1 に答える 1

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);  
    });
});
于 2013-01-20T13:23:55.433 に答える