Retrieve data from two databases and display the information from two separate arrays on a single ejs page after making two separate database calls

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.

Answer №1

To ensure proper sequencing of asynchronous functions in your code, it is advisable to store them in an array and utilize Promise.all for synchronization before rendering the page:

app.get('/', (req, res) => {

  let dataFetchers = []

  dataFetchers.push(dao.getAllSerie) // include first async function
  dataFetchers.push(dao.getCategorie) // add the second one

  Promise.all(dataFetchers) // wait for all promises to be resolved or rejected
    .then(dataArray => {
      let series = dataArray[0] // result from first promise
      let categories = dataArray[1] // result from second promise

      res.render('index', { // render only after obtaining all data
        series: series,
        categories: categories
      })
    })
    .catch(err => res.status(500).end())
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve a selection of data from the data.json file and mix it up

My webpage has a json data sheet containing multiple objects that I am currently showcasing. { "objects": [ ... ] } In terms of templating: $(function () { $.getJSON('data.json', function(data) { var template = $('#objectstpl') ...

Access a folder in JavaScript using Flask

I need to specify a directory in a script. $images_dir = '{{url_for('.../pictures')}}'; In my flask application directory structure, it looks like this: Root -wep.py -templates -gallery.html -static -pictures The images are stored ...

Encountered an issue with mapping data from a controller to a view in Angular.js

Currently, my application consists of only three small parts: a service that makes an http call to a .json file, a controller that receives data from the service and sends it to a view. Everything was working fine when I hard coded the data in my service. ...

What could be the reason for receiving [object object] from a JSON response?

Utilizing the datatables plugin, I am in need of refilling the table with ajax. To achieve this, I populate the table columns with the data retrieved from an ajax file (in json format) as shown in the following code snippet: $.get(select.data('url&a ...

Is it possible to conduct an auction in JavaScript without using the settimeout or setinterval functions?

I'm currently working on creating an auction site and I need help improving its speed and performance. I've been using setInterval and setTimeout functions for the countdown, but it's quite slow as a request is sent to the server every secon ...

Is there a way to include custom headers in the response of socket.io using express.js?

I have been attempting to override the CORS policy using the following code block: app.use('/\*', function (req, res, next) { res.header("Access-Control-Allow-Origin","*") res.header("Access-Control-Allow-Hea ...

Ensure the initial word (or potentially all words) of a statement is in uppercase in Angular 2+

Struggling with capitalizing words in an Angular 2 template (referred to as view) led to an error in the console and the application failing to load, displaying a blank page: Error: Uncaught (in promise): Error: Template parse errors: The pipe 'c ...

What is causing Mocha.js to be unable to locate the module?

Having trouble with mocha.js not being able to locate my path! Here's the directory structure I have set up for my node course project: ///////Root --package.json --node_modules/ --playground --server -server.js -db -models ...

Retrieve items within an array of objects in MongoDB using an array of IDs (using the $in operator in aggregation)

In my MongoDB database, I have a collection of stores [ { "_id" : ObjectId("6043adb043707c034d5363b7"), "shopId" : "shopid1", "appId" : "777", "shopItems" : [ { ...

Issue with retrieving data from MySQL database using PHP in Chart.js

I am currently facing an issue while trying to populate a chart using the ChartJS plugin with data from my MySQL database. I keep encountering the error message: mysqli_fetch_assoc(): Couldn't fetch mysqli_result in ... Despite using json_encode, ...

Inserting all 4 files simultaneously with just one database insert query

I am trying to upload 4 files at a time in a single insert database query. Can anyone suggest how to achieve this? Here is my code: $name_array = $_FILES['files']['name']; $tmp_name_array = $_FILES['files']['tmp_name ...

Encountering a formidable challenge: SyntaxError occurring due to an unexpected token in JSON at position 0 while attempting to send a

Currently, I am in the process of developing the backend functionality for my web application that involves creating blog posts. This development is inspired by a tutorial that I am following. The technologies being employed for this task include MongoDB, ...

Is there a way to create a custom column in Tabulator that displays a calculated value for every row?

Can a custom column be added with a calculated value for each row? For example, if col 1 has the value "3" and col 2 has the value "5", then I want a dynamic col 3 with a sum value of 8. I am utilizing Vue Tabulator. Below is my Table.vue component. <t ...

I need to press the button two times to successfully submit

I am experiencing a remote validation issue. When I click on the submit button without focusing on the text box, it triggers a remote ajax call for validation. However, when I press the submit button a second time, the form gets submitted. On the same cl ...

Vue warning: You are trying to access a property or method that is not defined on the instance but is being referenced during

The code snippet above was created to manage an event triggered by a button click var MainTable = Vue.extend({ template: "<ul>" + "<li v-for='(set,index) in settings'>" + "{{index}}) " + &qu ...

Unexpected addition of values to a list occurs when scrolling through a web element using Selenium

Having recently delved into Python, as well as programming in general, I am eager to extract data from a webelement that updates dynamically with scrolling using Selenium. A particular post on Stack Overflow titled Trying to use Python and Selenium to scro ...

How can I use JavaScript fetch to retrieve data from a JSON file based on a specific value?

I am looking to extract specific values from a JSON array based on the ID of elements in HTML. How can I achieve this? [ { "product": "gill", "link": "x.com", "thumbnail": "gill.jpg ...

Vue.js is unable to dispatch an event to the $root element

I'm having trouble sending an event to the root component. I want to emit the event when the user presses enter, and have the root component receive it and execute a function that will add the message to an array. JavaScript: Vue.component('inp ...

What is the best way to extract menu and submenu information from an array?

I'm in the process of building a webpage with the help of smart admin and I'm facing an issue with displaying left menu data properly. The data is being retrieved from an array and I need to arrange the menus and submenus based on the parent ID o ...

Guide: Highlighting a selected link in Navigation without redirecting the page can be achieved in AngularJS by utilizing

I have a list of links that I want to be able to highlight when clicked without redirecting to the page. Below is the code snippet: HTML <ul class="nav nav-list"> <li ng-repeat="navLink in navLinks" ng-class="navClass('{{navLink.Title ...