Cannot get valid list while using redis with node.

2019-09-06 08:39发布

问题:

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:

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

});