Currently, I am faced with a challenge where I need to render a page by passing two arrays that are populated by two separate database calls. It seems that when I only pass one array to the ejs page, everything works as expected.
For a single array, my approach is:
dao.getAllSerie().then((show) => {
res.render('index', {
series: show,
})
}).catch(() => res.status(500).end());
When following this method, the content gets rendered without any issues and the ejs page is successfully filled with values.
Now, the question arises: "How can I render two arrays that are filled with results of two different database calls?"
I attempted the following approach:
app.get('/', (req, res) => {
series = [];
categories = [];
dao.getAllSerie().then((show) => { series = show; })
.catch(() => res.status(500).end());
dao.getCategorie().then((category) => { categories = category; })
.catch(() => res.status(500).end());
// The issue here is that 'series' and 'categories' end up being null at the time of rendering.
res.render('index', {
series: series,
categories: categories
})
})
Unfortunately, both 'series' and 'categories' turn out to be null when trying to render the ejs page, indicating a lack of dynamic content. Is there a way to handle this asynchronous problem effectively?
Below are the functions for the database calls:
// Get all series from the database
exports.getAllSerie = function() {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM serie';
db.all(sql, (err, rows) => {
if (err) {
reject(err);
return;
}
resolve(rows);
});
});
};
// Get all categories from the database
exports.getCategorie = function() {
return new Promise((resolve, reject) => {
const sql = 'SELECT DISTINCT categoria FROM serie';
db.all(sql, (err, rows) => {
if (err) {
reject(err);
return;
}
resolve(rows);
});
});
};
I acknowledge that categories should ideally be in a separate table, but this setup is solely for experimentation purposes. Appreciate any assistance on resolving this matter. Thank you.