I need to wait for queries from a database I have in Postgres
from a function that uses a callback.
I have a function to get rows from the database (queries.js
):
const getRecipesByCategoryForSection = (callback, category) => {
pool.query("SELECT * FROM recipes WHERE category=$1 ORDER BY RANDOM() LIMIT 10;", [category], (error, results) => {
if (error) {
console.log(error);
throw error;
}
callback(results.rows);
})
}
As you can see, I am using a callback function to get the rows from the database. I want to use those rows to display them on one page, but displaying various categories. I use it in my server.js
in the following manner:
app.get("/recipes", function (req, res) {
var breakfasts = [];
var lunches = [];
var desserts = [];
db.getRecipesByCategoryForSection(function (rows) {
breakfasts = rows;
}, 'breakfast');
db.getRecipesByCategoryForSection(function (rows) {
lunches = rows;
}, 'lunch');
db.getRecipesByCategoryForSection(function (rows) {
desserts = rows;
}, 'snack');
res.render("recipes", {
breakfasts: breakfasts,
lunches: lunches,
snacks: snacks
});
});
But in this configuration, variables breakfasts
, lunches
, and desserts
contain, of course, nothing.
How do I set the function in the queries.js
in respect to callbacks so the function in server.js
would wait for the rows before executing the rest of the code?
I would be grateful for any help, I am quite new to this so any explanation and help would be very valuable. Thank you.