Redis 正在输出 true 而不是所需的值
Redis is outputting true instead of the desired value
我有 nodejs 运行 我想调用这个函数:
function name(id) {
var x = rclient.get(id, function(err, reply) {
return reply;
});
return x;
}
然而,当我尝试使用 console.log(name(1))
获取函数的输出时,输出是 true
,而不是存储在 redis 服务器上的值。这看起来很容易修复,但是,它让我难住了。
好吧,您正在使用回调,因此回调函数中的 return
值不会返回到 x
。
试试这个(取决于你的 redis 客户端,我假设你使用 node-redis
):
function name(id) {
return new Promise((resolve, reject) => {
rclient.get(id, function (err, reply) {
if (err) {
return reject(err);
}
resolve(reply);
});
});
}
// call with
name(1).then((value) => console.log(value)).catch((err) => console.log(err));
// better yet (inside async function)
async main() {
const value = await name(1);
}
</pre>
或者,帮自己一个忙,使用 handy-redis
(https://www.npmjs.com/package/handy-redis):
async function name(id) {
return rclient.get(id);
}
// call with the same as above
</pre>
本质上,您对 async/sync 调用有点困惑。 x
解析为 true
的事实很可能是 .get
方法的实现,而 不是 回调。
instead of the value stored on the redis server. this seems like a simple thing to fix, however, it has me stumped.
当我第一次开始使用 Node.js 时,我感觉很像你,与大多数语言相比它很奇怪,但是,你很快就会发现它更自然(尤其是使用 async/await 语法)
我有 nodejs 运行 我想调用这个函数:
function name(id) {
var x = rclient.get(id, function(err, reply) {
return reply;
});
return x;
}
然而,当我尝试使用 console.log(name(1))
获取函数的输出时,输出是 true
,而不是存储在 redis 服务器上的值。这看起来很容易修复,但是,它让我难住了。
好吧,您正在使用回调,因此回调函数中的 return
值不会返回到 x
。
试试这个(取决于你的 redis 客户端,我假设你使用 node-redis
):
function name(id) { return new Promise((resolve, reject) => { rclient.get(id, function (err, reply) { if (err) { return reject(err); } resolve(reply); }); }); } // call with name(1).then((value) => console.log(value)).catch((err) => console.log(err)); // better yet (inside async function) async main() { const value = await name(1); } </pre>
或者,帮自己一个忙,使用
handy-redis
(https://www.npmjs.com/package/handy-redis):async function name(id) { return rclient.get(id); } // call with the same as above </pre>
本质上,您对 async/sync 调用有点困惑。
x
解析为true
的事实很可能是.get
方法的实现,而 不是 回调。instead of the value stored on the redis server. this seems like a simple thing to fix, however, it has me stumped.
当我第一次开始使用 Node.js 时,我感觉很像你,与大多数语言相比它很奇怪,但是,你很快就会发现它更自然(尤其是使用 async/await 语法)