What I’m trying to do here is call the username from the database from the cookie, I tried to just call it though a regular function, but that doesn’t work since I have to wait on the data. then after send the data to the webpage. but my issue is just getting the data itself.
I don’t really have much experince with promises, so I’m trying to figure out what’s happening here. thanks for the help.
async function user(req, res) {
let key = req.cookies['cookie']
return new Promise((resolve, reject) => {
connection.query('SELECT * FROM accounts WHERE `key` = ?', [key], (error, results, fields) => {
if (error) {
return console.log(error)
}
if (results.length > 0) {
resolve(results[0].username)
}
});
}
)
}
async function grabinfo(req, res) {
res.render('dashboard', { title:'Dashboard', username: username});
const username = await user(req, res)
}
module.exports.grabinfo = grabinfo
The Error
(node:1463495) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'username' before initialization
at Object.grabinfo (/home/ubuntu/nodeprojects/website/modules/dashboard.js:45:58)
at /home/ubuntu/nodeprojects/website/router/app.js:37:15
at Layer.handle [as handle_request] (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/route.js:144:13)
at Route.dispatch (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/route.js:114:3)
at Layer.handle [as handle_request] (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/layer.js:95:5)
at /home/ubuntu/nodeprojects/website/node_modules/express/lib/router/index.js:286:22
at Function.process_params (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/index.js:348:12)
at next (/home/ubuntu/nodeprojects/website/node_modules/express/lib/router/index.js:280:10)
at SendStream.error (/home/ubuntu/nodeprojects/website/node_modules/serve-static/index.js:121:7)
(node:1463495) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli .html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1463495) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections t hat are not handled will terminate the Node.js process with a non-zero exit code.
2
Answers
The error message clearly says.
You are using the username constant before defining it.
javascript works top to bottom, not bottom to top so first initialize username then use it.