将 redis 与 node.js 一起使用时无法获取有效列表 [英] Cannot get valid list while using redis with node.js

查看:63
本文介绍了将 redis 与 node.js 一起使用时无法获取有效列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 node.js 并使用 redis 在服务器上缓存一些数据.

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

我的代码:

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

代码摘要:

调用 main 函数,它进一步调用另外两个函数(redis_set 或 redis_get).Redis_set 采用键值对,而 redis_get 采用指向数据的键.

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.

问题:

该集合完美运行,但问题在于 GET.我没有按照我在 redis 中设置的方式获取我的数据.我在 get 中使用了 JASON.parse(),因为我在设置数据时对数据进行了字符串化.

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.

推荐答案

从 redis 读取数据是一个异步操作.您不能从回调中返回值.您需要将回调传递给接收获取的值的 redis_get 函数.

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

并获得一个值:

redis_get("key", function(redis_items) {

});

这篇关于将 redis 与 node.js 一起使用时无法获取有效列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆