Search code examples
node.jspg

await with pg throws an error


I am following the example at node-postgres and trying to create a synchronous connection to postgres from nodejs

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/');

The node.js complains with the error:

   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

what do I do wrong (connecting through event handling works just fine)?


Solution

  • You need to mark function as async if you want to use await keyword inside. 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);