Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js and Redis

I am trying to link up a redis database with a Node.js application I am building to be able to store comments about items. I'm using the node_redis library to handle the connection. When I attempt to retrieve the comments out of the database however only "[true]" is returned. For testing purposes I have stuffed everything into one method and I have hardcoded the values in, but I still receive "[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;

}

Updated the code according to the tutorial and here is the result:

Retrieving the comment:

exports.getComment = function (id, callback){

  rc.hgetall(id, callback);

}

Adding the comment:

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

};

Code to render:

var a = [];
require('../lib/annotations').addComment("comment");
require('../lib/annotations').getComment("comment", function(comment){
    a.push(comment)
});
res.json(a);
like image 868
Chris Maness Avatar asked Dec 31 '25 05:12

Chris Maness


1 Answers

Node.js is asynchronous. Which means it asynchronously does the redis stuff, and then gets the result back in the callback function.

I suggest you read this tutorial and fully understand it before getting further: http://howtonode.org/node-redis-fun

Basically, this way won't work:

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

But it has to be this way:

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

This way, you use the API like this:

getComments( '1', function( results ) {
    // results are available!
} );
like image 196
Florian Margaine Avatar answered Jan 03 '26 03:01

Florian Margaine