0

I am working with node.js and using redis for caching some of the data on the server.

My code:

var client = redis.createClient();
client.on("error", function (err) {
    console.log("Error " + err);
});

client.flushall();

function redis_get(key){
    client.get(key, function(err, value) {
        if (err) {
        console.error("error");
        } else {
            return value;
        }
    });
}

function redis_set(key, value){
    client.set(key, JSON.stringify(value), function(err) {
        if (err) {
            console.error("error");
        }
    return true
    });
}

function main(){

    var new_items = [{"id": 1, "name": "abc"}, {"id": 2, "name": "xyz"}, {"id": 3, "name": "bbc"}];

    //set data in redis
    redis_set("key", new_items);

    //get data from redis
    var redis_items = redis_get("key");
}

Summary of code:

The main function is called, which further calls 2 other functions (redis_set or redis_get). Redis_set takes a key and a value pair whereas redis_get takes the key which points to the data.

Problem:

The set works perfectly but the problem is with GET. I am not getting my data in the way I had set it in redis. I have used JASON.parse() in get as I have stringify the data when i had set it.

1
  • In what form are you getting data then? Looks like you are trying to treat async function as synchronous. Or do client.set / client.get block execution? Commented Jan 1, 2013 at 13:22

1 Answer 1

1

Reading data from redis is an asynchronous operation. You can't return a value from the callback. You need to pass a callback to your redis_get function that receives the fetched value.

function redis_get(key, callback) {
    client.get(key, function(err, value) {
        if(err) {
            console.error("error");
        } else {
            callback(value); // or maybe callback(JSON.parse(value));
        }
    });
}

And to get a value:

redis_get("key", function(redis_items) {

});
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry but 2 things are still unclear; firstly callback? Is it another function? And the second part of your code
Any operation in nodejs that involves IO is asynchronous. So such an operation cannot return a value in the classical way. Instead, it executes a callback function provided by you and passes the result as an argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.