ExpressJS - 在router.get中调用外部函数并呈现其数据

时间:2017-11-16 14:42:24

标签: javascript mysql node.js express ejs

我需要调用函数以便将mysql查询数据呈现给我的视图,而不是在router.get

中包含查询函数

如何在function()内调用router.get,以便通过EJS或任何其他模板引擎呈现其查询输出?

index.js

function fdb(mypar) {
    obj = {}
    con.query(mypar, (err, rows) => {
        if (err) throw err
        obj = rows[0]
        console.log(obj)
        //rows data fetching OK using stored procedure get_all_1 when route '/' is called
    })
}

/* GET home page. */
router.get('/', function(req, res, next) {
    fdb('CALL get_all_1')
    console.log(obj) // {}

    to_render = { print: obj } 
    console.log(to_render) // { print: {} }

    res.render('index', to_render); 
    //it obviously cannot render anything
    //GET / 500 
});

index.ejs

<% print.forEach(function (qdata) { %>
    <tr>
        <td>
            <%= qdata.name %>
        </td>
        <td>
            <%= qdata.location %>
        </td>
    </tr>
<% }) %>

当我尝试通过obj内的fdb()函数调用router.get但是无法弄清楚如何操作该范围时,我以某种方式理解if (checkbox1.getOrElse("") == "checked" && checkbox2.getOrElse("") == "checked") { val checkboxIterable1: Iterable[String] = filegetter1 val checkboxFile1 = new File("checkboxFile1.csv") using(new FileWriter(checkboxFile1))(writer => fileGetter1.foreach { d => writer.write(d) }) fileGetter1 val checkboxIterable2: Iterable[String] = fileGetter2 val checkboxFile2 = new File("checkboxFile2.csv") using(new FileWriter(checkboxFile2))(writer => fileGetter2.foreach { d => writer.write(d) }) fileGetter2 val zipFile = zip("Zipped file", List("checkboxFile1.csv", "checkboxFile2.csv")) val zipFileName = "Zipped file" val zipToBArray = new BufferedInputStream(new FileInputStream(zipFileName)) val getByteArray = Stream.continually(zipToBArray.read).takeWhile(-1 !=).map(_.toByte).toArray InMemoryResponse( getByteArray, "Content-Type" -> "application/zip; charset=utf8" :: "Content-Disposition" -> s"attachment; filename=file.zip" :: Nil, cookies = Nil, code = 200) } 超出范围。

2 个答案:

答案 0 :(得分:2)

这样做。您可以使用回调函数。

When

答案 1 :(得分:2)

function fdb(mypar) {
  return new Promise((resolve) => {
    obj = {}
    con.query(mypar, (err, rows) => {
      if (err) throw err
      obj = rows[0]
      console.log(obj)
      resolve(obj);
    })
  });
}

/* GET home page. */
router.get('/', async function(req, res, next) {
  let obj = await fdb('CALL get_all_1')
  console.log(obj)

  to_render = { print: obj } 
  console.log(to_render)

  res.render('index', to_render); 
});