如何传递所有redis记录?

时间:2017-05-29 06:48:28

标签: node.js redis

我想将Redis中的所有记录传递给视图。我认为我对redis值做错了是因为我无法将其推送到数组或对象。

我试图这样:

app.get('/', function (req, res, next) {
var items = [];
  client.keys('*', function (err, obj) {

    for (var i = 0, len = obj.length; i < len; i++) {

        client.hgetall(obj[i], function (err, value) {
            if(typeof value === 'object'){
                items.push(value);
            }

        });

    }
    console.log(items); // returns empty array

});

   res.render('searchusers'); // need to pass the object here
});

当我控制台记录我得到的价值

  for (var i = 0, len = obj.length; i < len; i++) {

        client.hgetall(obj[i], function (err, value) {
            console.log(value);

        });

    }
 ------------ Result--------------

{ first_name: 'john123',
  last_name: 'foofoo',
  email: '323233',
  phone: 'foo' }

价值显然是一个对象......我是否需要对其值进行循环?或者有更简单的方法可以这样做。

1 个答案:

答案 0 :(得分:1)

那是因为您正在进行异步调用,请尝试以下代码:

app.get('/', function (req, res, next) {
    var items = [];
    client.keys('*', function (err, obj) {
        const hGetAll = function(i){
            if(obj[i]){
                client.hgetall(obj[i], function (err, value) {
                    if(typeof value === 'object'){
                        items.push(value);
                    }
                    hGetAll(i+1);
                });
            }else{
                console.log(items);
                // res.json(items); for JSON response
                res.render('searchusers', items);
            }
        }
        hGetAll(0);
});

我没有测试过,但它应该可行。您还可以使用Promises使其更具可读性。

相关问题