首页 > 解决方案 > Redis 在 nodejs 中返回 true

问题描述

我正在用打字稿编写一个 RESTful API,我正在尝试使用存储在 redis 中的已解析数据和另一个函数中的特定键。我遇到的问题是,我没有从redis接收实际数据,而是一直收到一个布尔值true。我尝试了很多谷歌搜索并阅读了 redis 文档,但不幸的是无济于事。现在有人在这里如何访问实际数据以便可以在另一个功能中使用它吗?我怀疑我在这里面临某种异步问题,但我并不完全确定。

例如,如果我尝试将响应绑定到变量,则会发生这种情况:

const key = something
const reply = client.mget(key);
console.log("This is the reply: " + reply);

This is the reply: true

兄弟,维克多

编辑:

所以基本上我将数据从 https.get 发送到对象处理程序,它将数据解析为我喜欢的形式,然后我将该对象字符串化并将其作为字符串发送到 redis,如下所示:

client.set(redisInfo, JSON.stringify(objecthandler(newdata)));

我目前获取数据的实际代码如下所示:

const getRedis = (rediskey: string, success: any, error: any) => {
    client.mget(rediskey, function (err: Error, reply: any) {
        if (!err) {
            success(reply);
        }
        else {
            error(err);
        }
    });
};

//My callback function that I'm trying to get to work so I can use the redis data in other functions
function getrediscallback(key: string) {
       getRedis(key, function success(reply: string): string {
       //This console.log actually returns the data that I want
        console.log("this is the reply: " + reply);
            return reply;
            },
function error(err: Error) {
    console.log("Something went wrong" + err);
});
}

所以当我在另一个函数中使用回调时,它看起来像这样:

const redisdata = getrediscallback("getCars");
//This gives me the value of undefined
console.log(redisdata)

这意味着回调函数实际上获取了实际数据,但是当我在另一个函数中使用回调函数时,它永远不会到达。

标签: node.jsasynchronousredis

解决方案


 import util from "util";
 import redisClient from "../config/redisConfig";
 let hgetall = util.promisify(redisClient.hgetall).bind(redisClient);
 await hgetall("Key")

推荐阅读