Node.js和Redis

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

Chris Maness:请更新您的问题,而不是我的答案 :) - Florian Margaine
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!
} );

@ChrisManess 在继续之前,请先阅读并理解教程。你应该了解异步的工作原理,并轻松找出代码中的问题所在。 - Florian Margaine
@ChrisManess 我编辑了我的答案,希望您可以轻松理解这个概念。 - Florian Margaine
@ChrisManess 这只是在redis函数中传递的。因此,redis函数将执行某些操作,一旦完成,它将使用参数中的正确数据运行callback函数。这就是为什么匿名函数将具有正确的结果。 - Florian Margaine
@FlorianMargaine 当我尝试这个时,它只返回一个空值。即使在设置之前也是如此。 - Chris Maness
@ChrisManess 你有看过教程吗?学完之后你的新代码是什么? - Florian Margaine
显示剩余4条评论

0

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

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接