首页 文章

使用NODE JS和BLUEBIRD从REDIS获取数据

提问于
浏览
0

我正在尝试获取特定键模式的所有条目并使回调发生整齐,我正在使用Bluebird . nodejs的redis客户端是项目的node_redis .

redis客户端中的代码是 -

exports.getAllRedisKeysA = function() {
  var res = rclient.keysAsync("client*").then(function(data) {
    // console.log(data);
  }).then(function(data) {
    var arrayResp = [];
    for (var element in data) {
      rclient.hgetallAsync(element).then(function(data) {
        arrayResp.push(data);
      });
    };
    return arrayResp;
    //  console.log(data);
  }).catch(console.log.bind(console));
  console.log(res); // gives an empty promise.
  return res;
}

并且以下面的方式从控制器调用此函数 -

var abc = rdata.getAllRedisKeysA();
// console.log(abc); // gives undefined

redis函数内的console.log输出给出了一个空承诺,并且没有任何内容返回给控制器 .

我在实施中遗漏了什么吗?

1 回答

  • 1

    LinusJaromanda对这个帮助我朝着正确方向前进的问题提出了一些真正有用的评论 . 我使用以下方法使用BlueBird Promise从REDIS获取我所需的数据,以及这是如何完成的 .

    The code below gets the required data from REDIS

    exports.getRedisKeyPattern = function(pattern){
    
    var allKeys = allKeysPattern(pattern).then(function(data){
      var arrayResp = [];
      var inptArr = [];
      var newdata = data.slice(1)[0];
      for(var i in newdata){
        inptArr.push(newdata[i]);
      };
      return new Promise.resolve(inptArr);
    });
    
    var valuePerKey = Promise.mapSeries(allKeys, function(dt){
      return getAllKeyContents(dt);
    }).then(function(res){
      return res;
    }).catch(function(err) { console.log("Argh, broken: " + err.message);
    });
    
    return new Promise.resolve(valuePerKey);
    }
    
    function getAllKeyContents(key){
      var data =  rclient.hgetallAsync(key).then(function(data){
          return data;
      }).catch(function(err) { console.log("Argh, broken: " + err.message); });
    
      var res = Promise.join(data, key, function(data, key){
          return {
              key: key,
              data: data
          };
        });
    
      return res;
    }
    

    从控制器,这个函数被调用 -

    var rdata = require('../../components/redis/redis-functions');
    rdata.getRedisKeyPattern("clients*").then(function(response){
          return res.status(200).json(response);
        });
    

    包含redis函数的.js文件包含在控制器文件中,以便可以使用函数 .

相关问题