Wednesday 30 January 2019

Question about undefined variable

Hey guys, I'm trying to build a webserver. I've never used Node before so I'm completely new to this.I have this block of code with an async function.router.post('/new', async (req, res) => { console.log('Received Post Request: '); console.log(req.body.name); console.log(req.body.description); console.log(req.body.abv); try{ const client = await db.getClient(); console.log('Client Checked Out'); const { rows } = await db.query('INSERT INTO testbeer(name, description, abv) VALUES($1, $2, $3)', [req.body.name, req.body.description, req.body.abv]); await db.query('COMMIT'); console.log('Added entry'); } catch(e) { await db.query('ROLLBACK'); throw e; } finally { db.releaseClient( client ); console.log('Client Released'); } res.render('new', { title: 'Add New Entry' }); }) When I post a request from my browser, I get the following error at "db.releaseClient(client)"(node:14880) UnhandledPromiseRejectionWarning: ReferenceError: client is not defined However, when I add a second variable (i.e. "client2 = client", noted by **), it works fine.router.post('/new', async (req, res) => { console.log('Received Post Request: '); console.log(req.body.name); console.log(req.body.description); console.log(req.body.abv); try{ const client = await db.getClient(); **client2 = client;** console.log('Client Checked Out'); const { rows } = await db.query('INSERT INTO testbeer(name, description, abv) VALUES($1, $2, $3)', [req.body.name, req.body.description, req.body.abv]); await db.query('COMMIT'); console.log('Added entry'); } catch(e) { await db.query('ROLLBACK'); throw e; } finally { db.releaseClient( client2 ); console.log('Client Released'); } res.render('new', { title: 'Add New Entry' }); }) Does anyone know why this is?

Submitted January 31, 2019 at 05:06AM by Integral_10-13_2xdx

No comments:

Post a Comment