如何将多个数组对象发送到ejs模板

时间:2017-01-23 19:03:57

标签: node.js express

metadata

这就是我所做的......但它仍然无法运作

2 个答案:

答案 0 :(得分:0)

您可以使用async库来解决问题。

var async = require('async');

var results2 = [];
var categories2 = [];

async.parallel({
  results: function(callback) {
    const query2 = client.query('SELECT * FROM entries ORDER BY id desc');
    query2.on('row', (row) => {
      results2.push(row);
    });

    query2.on('end', () => {
      callback(null, results2);
    })
  },
  categories: function(callback) {
    const query3 = client.query('SELECT * FROM categories ORDER BY id desc');
    // Stream results back one row at a time
    query3.on('row', (row) => {
      categories2.push(row);
    });

    query2.on('end', () => {
      callback(null, categories2);
    });
  }
}, function(err, results) {
  if (err) {
    return res.send(err);
  }
  return res.render('index2.ejs',results);
});

答案 1 :(得分:-1)

您如何使用async.parallel结果:

async.parallel({
  numbers: function(cb) { cb(null, [1, 2, 3]); },
  letters: function(cb) { cb(null, ['a', 'b']); }
},
function (err, results) {
  console.log(results); // "{ numbers: [ 1, 2, 3 ], letters: [ 'a', 'b' ] }"
});

所以在你的情况下:

async.parallel({
  results: firstQueryCB, 
  categories: secondQueryCB
}, 
function everything(err, results) {
  if (err) { throw err; // actually do something. }
  // your `results` is now `{results: [], categories: []}`
  res.render('index2.ejs', {
    results: results.results,
    categories: results.categories,
  });
})