将 redis hget 值存储到 nodejs 中的变量中 [英] Storing redis hget values into a variable in nodejs

查看:105
本文介绍了将 redis hget 值存储到 nodejs 中的变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const redis = require('redis');
var client = redis.createClient();

client.on('error', function(err){
  console.log('Something went wrong ', err)
});


var getResponse = (key, field) =>{
 client.hget(key,field, function(err,reply){
    if(!err) return reply; 
    else {
    console.log(err);
    }
  });
};

var s = getResponse("employee","b");
console.log(s);

所以当输出显示 undefined 时.我究竟做错了什么?如何将返回值存储到 s?

So when the output shows undefined. What am I doing wrong? How to store the return value to s?

推荐答案

您可以使用如下回调:

var getResponse = (key, field, success, error) =>{
    client.hget(key,field, function(err,reply){
        if(!err) {
           success(reply);
         }
       else {
          error(err);
        }
   });
};

getResponse("employee","b",function success(reply){
    //here you get the reply
}, function error(err) {
        //error
});

如果您使用的是 Node 6 或更高版本,则可以使用 promise 或 async await.您可以在以下链接中找到更多详细信息:http://exploringjs.com/es6/ch_promises.html

If you are using Node version 6 or above you can use promise or async await. You can find more details on the following link: http://exploringjs.com/es6/ch_promises.html

这篇关于将 redis hget 值存储到 nodejs 中的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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