NodeJS将2个查询传递给html

时间:2017-12-31 18:19:51

标签: node.js

我有一个由NodeJS创建的小应用程序。 在我根据URL呈现HTML之前,我需要来自我的数据库的信息。 但就我目前的方式而言,我只能在查询时执行。

  <div className='App'>
    {localStorage.userData === undefined
      ? this.renderLogin()
      : <Home logout={this.logout.bind(this)} deets=
        {localStorage.userData}/>}
  </div>

我试图将结果保存在变量上,但它不起作用。结果保留正确的数据。我通过将结果写入控制台来解决这个问题。

2 个答案:

答案 0 :(得分:0)

查询是异步函数。您可以使用嵌套回调函数执行查询,也可以使用async / await关键字。

答案 1 :(得分:0)

所有NodeJs io函数都是异步的,这就是为什么你没有看到渲染,因为它比你mongo查询更早发生。尝试使用Promises

&#13;
&#13;
app.get('/technology/:technology',function(req,res){    

     MongoClient.connect('mongodb://xx.xxx')
    .then(client => {
        const db = client.db('test');      
        return Promise.all([
            db.collection('col1').find().toArray(),
            db.collection('col2').find().toArray()
          ])
     })
     .then([res1,res2] =>{
        res.render('technology',{tech1:res1,tech2:res2});
     })
     .catch(err => console.log(err))
   
});
&#13;
&#13;
&#13;