all I\'m pretty new to node and I just learned about the async and await function offered in javascript. I\'m trying to implement this method in the code snippet attached be
You have no return
statement in your displayDB
function.
Normally this would cause a function to return undefined
, but because you declared it async
, it causes it to return a Promise that is immediately resolved.
If you want it to wait until the database query is complete, then you need to explicitly return a new Promise
which you resolve
when you are ready (i.e. after you have called connection.end()
).
You need to return a promise from the async function displayDB
if you want to use the await
keyword in test, you need to learn how promises work first. Pseudo code :
var displayDB = () => {
return new Promise((resolve,reject)=>{
connection.query('SELECT * FROM products', (err, resp) => {
if (err) {
reject(err)
} else {
const table = [];
resp.forEach((product) => {
obj = {
'Product ID': product.productID,
'Category': product.category,
'Price': product.price,
'Stock': product.stockQuantity
}
table.push(obj)
})
resolve(table)
}
})
})
}
var test = async () => {
try{
console.table(await displayDB())
}catch(e){
console.log(e)
}
connection.end()
}
test()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise