3

我正在尝试将 redis 数据库与我正在构建的 Node.js 应用程序链接起来,以便能够存储有关项目的评论。我正在使用 node_redis 库来处理连接。当我尝试从数据库中检索评论时,只返回“[true]”。出于测试目的,我将所有内容都塞进了一个方法中,并且我已经硬编码了这些值,但我仍然收到“[true]”。

exports.getComment = function (id){

var comments = new Array();

rc.hmset("hosts", "mjr", "1", "another", "23", "home", "1234");

comments.push(rc.hgetall("hosts", function (err, obj) {

    var comment = new Array();

    if(err){
        comment.push("Error");
    } else {
        comment.push(obj);
    }

    return comment;
}));

return comments;

}

根据教程更新了代码,结果如下:

检索评论:

exports.getComment = function (id, callback){

  rc.hgetall(id, callback);

}

添加评论:

exports.addComment = function (id, area, content, author){

//add comment into the database
rc.hmset("comment", 
         "id", id, 
         "area", area, 
         "content", content,
         "author" , author,
         function(error, result) {
            if (error) res.send('Error: ' + error);
         });

//returns nothing

};

渲染代码:

var a = [];
require('../lib/annotations').addComment("comment");
require('../lib/annotations').getComment("comment", function(comment){
    a.push(comment)
});
res.json(a);
4

2 回答 2

2

Node.js 是异步的。这意味着它异步执行 redis 的工作,然后在回调函数中返回结果。

我建议您阅读本教程并在进一步了解之前完全理解它:http: //howtonode.org/node-redis-fun

基本上,这种方式是行不通的:

function getComments( id ) {
    var comments = redis.some( action );
    return comments;
}

但它必须是这样的:

function getComments( id, callback ) {
    redis.some( action, callback );
}

这样,您可以像这样使用 API:

getComments( '1', function( results ) {
    // results are available!
} );
于 2012-06-21T13:27:16.327 回答
0

当调用 addComment 时,问题出在实际的 Redis-Node 库中,如下所示。

require('../lib/annotations').getComment("comment", function(comment){
    a.push(comment)
});

此调用缺少回调函数中的参数。第一个参数是错误报告,如果一切正常,应该返回 null,第二个参数是实际数据。所以它的结构应该像下面的调用。

require('../lib/annotations').getComment("comment", function(comment){
    a.push(err, comment)
});
于 2012-06-26T14:19:35.287 回答