Node.js 在请求数据库查询后呈现HTML文件。(nodes.js、pug.js、pocket.db)

Node.js 在请求数据库查询后呈现HTML文件。(nodes.js、pug.js、pocket.db),node.js,asynchronous,pouchdb,Node.js,Asynchronous,Pouchdb,函数的作用是返回一个名为“name”的对象。但它不是由pug.js渲染的 为什么pug.js不使用doc.name呈现模板?正如@Paul的评论所述,您不能简单地从异步函数调用返回值。您应该使用回调或承诺: 回调方式为: var url = require('url'); var pug = require('pug'); var PouchDB = require('pouchdb'); var db = new PouchDB('http://127.0.0.1:5984/data');

函数的作用是返回一个名为“name”的对象。但它不是由pug.js渲染的


为什么pug.js不使用doc.name呈现模板?

正如@Paul的评论所述,您不能简单地从异步函数调用返回值。您应该使用回调承诺

回调方式为:

var url = require('url');
var pug = require('pug');
var PouchDB = require('pouchdb');

var db = new PouchDB('http://127.0.0.1:5984/data');

var doc = {
  "_id": "mittens",
  "name": "Mittens",
};

function query() {db.get('mittens', function (error, doc) {
  if (error) {
    console.log('Ops! There is an error.');
  } else {
    console.log(doc);
    return doc;
  }
});
}

module.exports = {
    handleRequests: function(request, response) {
        response.writeHead(200, {'Content-Type': 'text/html'});
        var path = url.parse(request.url).pathname;
        console.log(path);
        switch (path) {
            case '/':
                response.write(pug.renderFile('./views/index.pug', query()));
                response.end();
                break;
然后:


阅读更多:如果您愿意,可以用承诺的方式来实现。

因为您对数据库的查询是异步的。该文档仅在db.get回调函数的作用域中。
function query(item, callback) {
  db.get(item, function (error, doc) {
    if (error) {
      callback(error, null);
    } else {
      callback(null, doc);
    }
  });
}
case '/':
  query('mittens', function(err, doc) {
    if (err) throw err;
    response.write(pug.renderFile('./views/index.pug', doc));
    response.end();
  }
  break;