简体   繁体   English

如何在express.js中呈现redis记录?

[英]How to render redis records in express.js?

I am new to node.js and express.js. 我是node.js和express.js的新手。 I know this is a little bit silly, but I really don't know how to solve this problem. 我知道这有点愚蠢,但是我真的不知道如何解决这个问题。 Hope there is someone can help me. 希望有人可以帮助我。

I have some information stored in Redis. 我在Redis中存储了一些信息。

redis 127.0.0.1:6379> hgetall "store1"
1) "apple"
2) "10"
3) "banana"
4) "15"
5) "pear"
6) "20"
7) "name"
8) "A Street"
redis 127.0.0.1:6379> hgetall "store2"
1) "apple"
2) "30"
3) "banana"
4) "40"
5) "pear"
6) "50"
7) "name"
8) "B Street"

I want to show these information in a table. 我想在表格中显示这些信息。 Using express.js, I created the following routes file. 使用express.js,我创建了以下路由文件。

routes/report.js 路线/report.js

var redis = require('redis'),
    redisclient = redis.createClient();

exports.index = function(req, res){
  redisclient.on("error", function (err) {
      console.log("Error " + err);
  });

  var reports = [];
  redisclient.keys("*", function(err, stores) {
    for (var store in stores) {
      redisclient.hgetall(store, function(err, figures) {
        reports.push(figures);
      });
    }
  });

  res.render('report', { title: 'Store Report', reports: reports });
};

And also the following jade view files. 还有以下jade视图文件。

views/report.jade views / report.jade

h1= title
table(class="table table-striped table-condensed")
  thead
    tr
      th store
      th apple
      th banana
      th pear

  tbody
  - each report in reports
    !=partial('partials/record', {store:record.name, apple:record.apple, banana:record.banana, pear:record.pear})

views/partials/record.jade 视图/部分/record.jade

tr
  td= store
  td= apple
  td= banana
  td= pear

When I open localhost:3000/report , I get the table structure with no content. 当我打开localhost:3000/report ,我得到的表结构没有内容。

I understand that redis call is async. 我了解Redis呼叫是异步的。 The report.js file rendered the report.jade before redis return any result. 在redis返回任何结果之前, report.js文件呈现了report.jade

Would anyone please to tell me how can I solve this problem? 谁能告诉我如何解决这个问题?

Thanks! 谢谢!

Try use the async module, execute a callback to render the results when all IO operations are completed. 尝试使用异步模块,在所有IO操作完成后执行回调以呈现结果。

Code example from async README: 来自异步自述文件的代码示例:

async.parallel([
    function(){ ... },
    function(){ ... }
], callback);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM