等待与pg抛出错误

时间:2018-01-28 20:47:35

标签: node.js pg

我正在关注node-postgres的示例并尝试创建与nodejs的postgres的同步连接

var http = require("http");

const { Pool, Client } = require('pg')
const connectionString = 'postgresql://x:x@localhost:5432/x'

http.createServer(function (req, res) {
   res.setHeader('Content-Type', 'text/html');

   const pool = new Pool({ connectionString: connectionString, })
   await pool.connect()

   const res = await pool.query('SELECT NOW()')
}).listen(3000);

console.log('Server running at http://127.0.0.1:3000/');

node.js抱怨错误:

   await pool.connect()
         ^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

我做错了什么(通过事件处理连接工作正常)?

1 个答案:

答案 0 :(得分:1)

如果您想在里面使用async关键字,则需要将功能标记为awaitMDN

  

await运算符用于等待Promise。它只能用于   在异步功能中。

http.createServer(async function (req, res) { // NB!
   res.setHeader('Content-Type', 'text/html');

   const pool = new Pool({ connectionString: connectionString, })
   await pool.connect()

   // also you were shadowing res argument
   // const res = await pool.query('SELECT NOW()')
   const now = await pool.query('SELECT NOW()')
   res.send(now); 
}).listen(3000);