如何为Node和pg-promise分开控制器和数据库查询

时间:2018-06-26 06:53:07

标签: javascript node.js postgresql express pg-promise

我正在编写一个Web应用程序,以使用NodeJS,express和pg-promise来显示包含PostgreSQL数据库内容的网页。

我有一个名为“ db / location.js”的数据库Javascript,可以查询位置表。

var db_global = require('./db');  # db.js is for building the database connection
var db = db_global.db;

var locationList = [];

// add query functions

module.exports = {      
  getAllLocationList: getAllLocationList,
  locationList: locationList
};

function getAllLocationList() {
  db.any('select * from location')
    .then(function (data) {
        console.log(data);
        locationList = data;
    }
  );
}

在路线文件夹中,我有一个名为“ locationRoute.js”的路线javascript。

var express = require('express');
var router = express.Router();

var db = require('../db/location');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/* GET the map page */
router.get('/locations', function(req, res) {
  db.getAllLocationList();
  console.log(db.locationList);

  res.render('locations', {
    title: "Express and Leaflet API", // Give a title to our page
    //jsonData: db.getAllLocations // Pass data to the View
    jsonData: db.locationList // Pass data to the View
  });
});

module.exports = router;

调用“ http://localhost:3000/locations”时,应该渲染“ locations.jade”,以便在表中显示“ db.locationList”。

我的问题是“ console.log(db.locationList);”总是在查询完成之前被调用。这导致“ db.locationList”(jsonData)为空。

我不想将控制器层与数据库层搞混,但是如何解决该问题?

1 个答案:

答案 0 :(得分:0)

我认为您应该将db / location.js更改为类似的内容...

function getAllLocationList() {
  return db.any('select * from location');
}

然后,您将在路线中执行类似的操作...

router.get('/locations', function(req, res) {
  db.getAllLocationList()
   .then(function(data) {
      res.render('locations', {
          title: "Express and Leaflet API", // Give a title to our page
          jsonData: data // Pass data to the View
      });
  });
  ...

在您的示例console.log(db.locationList);中在数据可用之前运行,因为它是异步的。它不像您期望的那样工作。

相关问题