I am new to node/js and I was wondering what I should do to fix my DB call. At the moment the call goes to return all data from my Postgres DB but when I try to store it the values are not yet returned. How should I go about structuring my code so I can wait until the values get stored so that when that info is passed to the next variable it's available? If you look below, you can see that the returnedOrders
field will have the undefined
value since the value from the db is still being fetched before it gets filled.
function insertOrder() {
dbConnector.connectToDB();
const returnedOrders = await dbConnector.retrieveAllOrders();
console.log("The returned orders" , returnedOrders);
}
function connectToDB() {
conn.connect().then((success, error) => {
if(error) {
console.log(`There was an error connecting because: ${error}`);
}else {
console.log(`Successfully connected to the database: ${success}`);
}
});
}
function retrieveAllOrders(){
const query = `SELECT * from food.pizza`;
conn.query(query).then((results, error) => {
if(error) {
console.log(`There was an error due to: ${error}`);
return;
}
console.log("Successfully connected. Running first query");
console.log(`Results are: ${JSON.stringify(results.rows[0], null , 2)}}`)
conn.end();
return results;
})
.catch((error) => {
console.log(`Unable to retrieve query due to: ${error.message}`)
})
}
This is the output from my terminal. Here you can see the order things happen in
node app.js
The returned orders undefined
Successfully connected to the database: [object Object]
Successfully connected. Running first query
Results are: { Here will be the results from the database. }