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 below. From my understanding, the database response should first print out to the console and then the "done", but I can't get it to work. Any help would be greatly appreciated.
Please also try to explain what you did to fix it, because I want to understand what I'm doing wrong.
var mysql = require("mysql");
const cTable = require('console.table');
var connection = mysql.createConnection({
host: "localhost",
port: 8889,
user: "root",
password: "root",
database: "testDB"
})
connection.connect((err, fields) => {
if (err) {
return console.log(err.code);
}
});
var displayDB = async () => {
connection.query('SELECT * FROM products', (err, resp) => {
if (err) {
return console.log(err.code);
} else {
table = [];
resp.forEach((product) => {
obj = {
'Product ID': product.productID,
'Category': product.category,
'Price': product.price,
'Stock': product.stockQuantity
}
table.push(obj)
})
console.table(table)
connection.end()
}
})
}
var test = async () => {
var x = await displayDB()
console.log('done')
}
test()
connection.queryreturns a promise. I haven't looked in a while, but I don't think the MySQL node module does. So you would need to wrap that in a promise and return the promise from the function.connection.querydid return a promise, since the return value ofconnection.queryis ignored insidedisplayDB.