等待 pg 抛出错误
await with pg throws an error
我正在按照 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
我做错了什么(通过事件处理连接工作正常)?
如果你想在里面使用await
关键字,你需要将函数标记为async
。 MDN。
The await
operator is used to wait for a Promise
. It can only be used
inside an async function.
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);
我正在按照 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
我做错了什么(通过事件处理连接工作正常)?
如果你想在里面使用await
关键字,你需要将函数标记为async
。 MDN。
The
await
operator is used to wait for aPromise
. It can only be used inside an async function.
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);