Node.js等待postgres响应客户端请求

时间:2017-02-10 22:15:01

标签: javascript node.js postgresql

我正在使用安装了Express和pg的Node.js构建REST API,并在本地运行PostgreSQL数据库。我理解JavaScript的异步性质,但是我不确定我正在响应请求的方法的有效性。看看我的代码:

/* index.js */
territoryService.initTerritoryService();

var http = require("http")
var express = require("express")
var app = express()
app.use(express.static(__dirname + "/"));
var port = process.env.PORT || 5000;
var server = http.createServer(app);
server.listen(port);

app.get("/nearby", function(req, res){
  var lat, lng;
  lat = parseFloat(req.query.lat);
  lng = parseFloat(req.query.lng);
  var respObj = territoryService.getNearbyTerritory(lat, lng, res);
});

/* territoryService.js */
module.exports = {
  initTerritoryService: function(){
    territoryDao = require("../dao/territoryDao.js");
    territoryDao.initTerritoryDao();
    console.log("Territory Service instantiated");
  },

  getNearbyTerritory(lat, lng, res){
    var dbRes = territoryDao.getNearbyTerritory(lat, lng, res);
    return dbRes;
  }
};

/* territoryDao.js */  
module.exports = {
  initTerritoryDao: function(){
    pg = require('pg');
    async = require('async');
    client = new pg.Client();
    var connectionString = 'postgres://username:password@localhost/table';
    pg.connect(connectionString, function (err, client, done) {
      if (err) throw err;
      console.log("Database connected");
    });
    console.log("Territory DAO instantiated");
  },

  getNearbyTerritory: function(lat, lng, res){
    var queue = [];
    queue.push(client.query.bind(client, 'SELECT * FROM territories WHERE id=39321797'));
    async.series(queue, function (err, results) {
      res.send(results);
    });
  }
};

我是否通过res从请求合法的初始路径开始,或者这是不好的做法?我这样做是为了响应pg查询完成,因为调用是异步的。

0 个答案:

没有答案