Dynamically render data in node.js

时间:2018-05-13 22:02:49

标签: node.js asynchronous render

This is a typical route in node.js that has a pseudo-code to connect to a database, get some data using a query and then pass them to a page to be rendered,

router.get('/', function(req, res){
  db-connect(function(err, db) {
    if (err) {
      return console.log('error');
    }
    db.query('select * from table', function(err, results){
        if (err) {
          return console.log('error');
        }
        res.render('index',{
            'title':'my title',
            'pageHeader': 'my header',
            'results': results //dynamic ???
        });
    });
  }); //connect
});//router get

I am using this pseudo-code to ask a general question :

The results data are dynamic, maybe the query will take a while, so the results do not get to the page fast, so I guess the rendering will also take a while.

How can I render static data immediatly (title and pageHeader) and the dynamic part (results) as soon as it is ready ?

Do I have to use another function or another syntax?

Thank you

1 个答案:

答案 0 :(得分:1)

res.render填充您的模板并将其发送到客户端(浏览器)。你不能发送更多"当它在稍后阶段准备就绪时。

让客户端等待数据,或先发送你的标题和标题,然后在浏览器上使用XHR(javascript)来完成剩下的工作。

相关问题