2012-06-21 37 views
3

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

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

克里斯Maness直言不讳:请更新您的问题,不是我的答案:) –

回答

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) 
}); 
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! 
}); 
+0

换句话说,返回的意见再来评论 – ControlAltDel

+0

之前发生的事情,'return'发生之前的数据都是甚至设置(我敢肯定'当返回完成时,hmset没有完成)。 –

+0

那么如何确保hmset发生在hmget之前 –