0
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;

The query() function is returning an Object with "name". But it isn't rendered by pug.js.

Why pug.js do not render the Template with doc.name?

Marcel
  • 199
  • 1
  • 18
  • 2
    Because your query to pouchdb is asynchronous. The doc is only in scope inside the db.get callback function. – Paul Feb 03 '17 at 13:24

1 Answers1

0

As stated in comments by @Paul you couldn't simply return a value from an asynchronous function call. you should use callbacks or promises:

The callback way:

function query(item, callback) {
  db.get(item, function (error, doc) {
    if (error) {
      callback(error, null);
    } else {
      callback(null, doc);
    }
  });
}

Then:

case '/':
  query('mittens', function(err, doc) {
    if (err) throw err;
    response.write(pug.renderFile('./views/index.pug', doc));
    response.end();
  }
  break;

Read More: How do I return the response from an asynchronous call? And implement promise way if you prefer.

Community
  • 1
  • 1
dNitro
  • 5,145
  • 2
  • 20
  • 45