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

Utilizing Angular and Express for routing with the seamless integration of html5mode

I'm facing an issue with making angular and express routing work together with html5mode enabled. When I change state from '/' to my admins state, everything works fine until I refresh the page. Then I only get a json result of admins but my ...

Searching for corresponding items in multi-dimensional arrays using Javascript

For my project in Javascript, I am facing the challenge of matching entire arrays. In this scenario, I have a userInput array and my goal is to locate a similar array within a multi-dimensional array and display the match. var t1 = [0,0,0]; var t2 = [1,0, ...

Guide to setting up a Cordova and TypeScript project using the command line interface

For my mobile application development, I rely on Cordova and execute cordova create MyApp in the command-line to initiate a new project. I am familiar with JavaScript but now require TypeScript for my project. Please assist me in setting up a Cordova pro ...

What is the process for linking a SQL server to the app.js file?

I currently have a directory named NEsql, which is located within another folder named sqlnames1. Inside the NEsql folder are the following individual files. sqlcreatedb.js var mysql = require('mysql'); var con = mysql.createConnection({ hos ...

Am I on the right track with my service definition in Angular?

(function(){ angular.module('myApp',[]) })(); (function(){ angular.module('myApp.dashboard',[]) })(); (function(){ angular.module('myApp.value',[]) })(); (function(){ 'use strict'; angular.modu ...

Is it possible to use nodemailer locally with NodeJS? The issue is that the greeting emails are not being received

Every time I attempt to send an email using nodemailer within my local network, I encounter the following error: *Greeting never received at SMTPConnection._formatError (C:\Users\PI_TEAM\Desktop\node_modules\nodemailer\lib ...

The Promise.all() function does not wait for the map function to finish resolving

Here is the code snippet that I am currently working with: const router = require("express").Router(); const Post = require("../models/Post"); const User = require("../models/User"); router.get("/timeline/all", asyn ...

What are the steps for implementing CORS?

I recently attempted to set up Ajax calls and stumbled upon the following code snippet: <!DOCTYPE html> <html> <body> <p id="demo">Let AJAX update this text.</p> <button type="button" onclick="loadDoc()">Updat ...

Leveraging and utilizing TypeScript npm packages

My goal is to create shared code in TypeScript, package it as an npm package, and easily install it. I attempted to create an external library like this: export class Lib { constructor(){ } getData(){ console.log('getting data from l ...

Issue with People Picker directive causing AngularJS validation to fail

I have implemented a SharePoint client-side people picker in my form using the directive from this GitHub repository. However, I am facing an issue where the validation of my form fails and the button remains disabled. When I remove the field, the validati ...

Incorporating numerous dropdown menus to a table filled with data retrieved from a database

I have implemented a dynamic table that adds a new row at the end when a button is clicked. One of the columns in the table contains a dropdown list, and I want this dropdown list to display values from a database. This is how I am constructing my table ...

Create a random number within a specified range using a different number in JavaScript

I am looking for a unique function that can generate a number within a specified range, based on a provided number. An example of the function would be: function getNumber(minimum, maximum, number) { ... } If I were to input: getNumber(0, 3, 12837623); ...

Animating text with a shake effect using JQuery

I am attempting to create a shake effect on my text input field when validation fails. While I have achieved the shake effect, I am unsure how to customize the default values for direction, distance, and times. Additionally, I believe there is an error i ...

Send data in JSON format from an AngularJS client to an Express server

Having an issue when trying to send a JSON Object from an AngularJS $http service to an Express Server. The server receives an empty object: "{}" I've looked at this topic, but it hasn't resolved my problem: angular post json to express This is ...

Issue with Google Charts - Chart is unable to render because data table has not been defined

Using Ajax, I attempted to set an Interval for my Google Chart, but unfortunately, the Chart is not being drawn. Instead, I repeatedly receive the error message: "Data table is not defined." every 5 seconds. If you want to see a screenshot of the error mes ...

Tips for creating an array within an AngularJS Service and effectively sharing it across two controllers

I have two controllers, FirstController and SecondController, along with a service defined as follows: app.factory('Data', function(){ return []; }); In both controllers, I am utilizing the service in this manner: app.controller("FirstCont ...

Make sure to only update the state in useEffect after retrieving the data from the localStorage

Trying to troubleshoot the continuous looping and crashing issue in my app caused by passing variables in the dependency array of the useEffect hook. These variables are state variables from the context provider. The goal is to make the useEffect hook run ...

The Jquery .remove() function will only take effect after the second click

I am currently working on implementing a notifications feature using bootstrap popover. The issue I am facing is that after a user clicks on a notification, it should be removed. However, for some reason, it requires two clicks to actually remove the notif ...

How can I retrieve an array from an object containing both a property and an array in TypeScript?

One of my objects always consists of a property and an array. When I use the console.log(obj) method to print it out, it looks like the following example: ProjectName: MyTest1 [0] { foo: 1, bar: 2} [1] { foo: 3, bar: 4} [2] { foo: 5, bar: 6} Alternat ...

If the server goes offline, it will not produce an error message

Running a factory in AngularJS angular.module('app.services',[]) .factory('myFactory', function($http){ return { getData: function(){ return {animal: 'dog'} }, isUser: function() ...