我是第一次使用 node.js 和 redis 构建一个非常简单的客户端/服务器应用程序。在成功启动我的 redis 客户端和我的 http 服务器后,我尝试用我的 redis 客户端做一个简单的 SET/GET。
我先做:
client.set('apple', 10, redis.print);
它返回一个 Reply:Ok
。
紧接着,我执行:
client.get('apple', function(err, reply) {
count = parseInt(reply);
return count;
});
奇怪的是,在打印出 count
时,我得到了 undefined
。但是,如果我使用 redis.print
,例如:
client.get('apple', redis.print);
Reply: 10
在控制台中返回。如果我执行 console.log(count)
,10
也会显示。
我想也许我误用了模块中的 set 函数,但在引用了这两个函数之后,我不确定是什么导致了我的错误:
最佳答案
upon printing out count, I get undefined.
client.get('apple', function(err, reply) {
count = parseInt(reply);
return count;
});
console.log(count); // is this where you get undefined?
// count at this point is, in fact, undefined,
// because it's set in a callback which was not yet fired.
我不在 node.js 中编程,所以我不确定从回调中返回计数的好处。它将返回到哪里?不应该是这样的吗?
client.get('apple', function(err, reply) {
count = parseInt(reply);
// do something with the count here. Print it or whatever.
});
或者您可以将它捕获在一个闭包中,但是您需要以某种方式等待回调返回并设置变量。怎么做 - 我不知道。
var count = null;
client.get('apple', function(err, reply) {
count = parseInt(reply);
});
// TODO: wait for callback
console.log(count);
关于javascript - Redis GET 函数返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21701561/