【发布时间】:2019-02-22 02:39:53
【问题描述】:
我正在使用 typescript 编写一个 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)
这意味着回调函数实际上得到了实际的数据,但是当我在另一个函数中使用回调函数时,它永远不会到达。
【问题讨论】:
-
请编写插入redis的代码。这样任何人都可以检查并让您知道是否有问题
-
redis 使用哪个客户端库?那个mget方法同步吗?
-
需要更多关于您为密钥设置的值的信息?您使用的是哪个客户端库?
-
我添加了更多应该(希望)回答您的问题的信息,谢谢!
-
只使用“.get”方法而不是mget。
标签: node.js asynchronous redis