Having trouble invoking an established route within a different route in an Express JS project

While working with an Express JS application connected to a mySQL database, I encountered an issue when trying to fetch data from a pre-defined route/query:

// customers.model.js
CUSTOMERS.getAll = (result) => {
    let query = "SELECT * FROM customers"

    sql.query(query, (err, res) => {
        if (err) {
            console.log("error: ", err)
            result(null, err)
            return
        }

        result(null, res)
    })
}

// customers.controller.js

// The GET customers route is set up to display all the available customer data.

const CUSTOMERS = require("../models/customers.model.js")

exports.findAll = (req, res) => {
    return CUSTOMERS.getAll((err, data) => {
        if (err)
            res.status(500).send({
                message: err.message ||
                    "Some error occurred while retrieving customers...",
            })
        else res.send(data)
    })
}

In payments.controller.js, my aim is to retrieve all users initially in order to manipulate the data:

// payments.controller.js

// The GET payments route is designed to fetch customer data, perform operations on it, and output calculated results based on this data

const CUSTOMERS = require("../models/customers.model.js")

exports.calculateAll = (req, res) => {

    const customers = CUSTOMERS.getAll((err, data) => {
        console.log('this always has correct data', data)
        if (err) return err
        else return data
    })

    console.log('this is always undefined', customers)

    ...
    
    res.send(whatEverCalculatedData)...
}

However, I constantly encounter the issue of data being undefined. What could possibly be wrong with my implementation above, and how should I correctly invoke one route inside another?

I've noticed similarities with this question, but I'm struggling to apply solutions to my specific scenario.

Answer №1

Your issue is likely due to the asynchronous nature of your function calls. It is important to ensure that your data is fetched and ready before proceeding with rendering the results.

Consider using Promises or async/await syntax for handling asynchronous operations.

Here is an example:

CUSTOMERS.getAll = async () => {
    const query = "SELECT * FROM customers";

    try {
      return await sql.query(query);
    } catch (e) {
       console.log(`An error occurred while fetching customers: ${e.message}.`);
       return null;
    }
}



exports.calculateAll = async (req, res) => {
    try {
        const data = await CUSTOMERS.getAll();
        res.send(whatEverCalculatedData);
    } catch (e) {
       res.send(`Something went wrong: ${e.message}.`);
    }
}

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

Issue with passing props to screen not displaying on initial load

Greetings, I'm a newcomer to the world of react native and currently facing an issue: const Tab = createMaterialTopTabNavigator(); export const CurriculumMenu = ({navigation, item}) => { const data = item.Title; console.log(data) return ( ...

ExpressJS - Error Handler Fails to Catch Any Errors

I am facing an issue with my error handler as shown below: export const errorHandler = ( error: Error, req: Request, res: Response, next: (error: Error) => void, ) => { console.log("TEST"); next(error); } Although ...

The presence of Firefox Marionette has been identified by hCaptcha

Whenever I go on indeed.com using the firefox web driver in Marionette mode, I keep encountering an hCaptcha popup. In an attempt to avoid this, I experimented with a user script that alters the navigator.webdriver getter to return false right at the sta ...

Exploring the potential of nested arrays within checkbox inputs

I'm struggling with extracting a nested array from an input value of a checkbox. How should I handle this situation? Here are the values: const othersOptions = [ {procedure:'ORAL PROPHYLAXIS',price: 1000}, {procedure:'TOOTH RESTORATION ...

CSS and JavaScript dropdown malfunctioning due to a position swap in internal CSS

This example demonstrates functionality .c1 { background-color:red; position:relative; } .c2 { background-color:blue; position:absolute; height:50px; width:100px; display:none;} .show { display:block; } <body> <button ...

Switch the website title as soon as the user looks away from the tab

How can I capture the user's attention and bring them back to my website when they are on a different tab? I really like the effect used on sephora.pl where an alert pops up with the message 'What are you waiting for?' when you switch tabs. ...

To implement a filter in MongoDB, make sure to specify a function argument before

Utilizing TypeScript, Node.js, Mongoose, and MongoDB in my project. I have a function that resembles the following: async function getAllBooks(title?: string, authorName?: string, sortBy?) { const books = await bookModel.find().sort(); return book ...

Personalized design created using v-for

I have an array being passed through v-for and I want to use the values within the "style" attribute. Essentially, I need to append the value from v-for to style:"left"+EachValue+"px", but I'm having trouble with the syntax. I'm unsure if this ap ...

What is the method for eliminating PHP $_SESSION using AJAX?

I am facing an issue with removing an array within a PHP Session variable using AJAX. Here is the process I follow: HTML: <a href="#" onclick="delete_pix(false, '1', false, '1.jpg');">remove</a> JavaScript: functio ...

Exploring jQuery Mobile - What Causes an Empty State?

Using $.mobile.navigate("#test-page", {id:123}) for navigation to a secondary page seems to be successful. The transition between pages is smooth.... but the state remains empty! According to the documentation, the state should contain all necessary info ...

Adjusting the settimeout delay time during its execution

Is there a way to adjust the setTimeout delay time while it is already running? I tried using debounceTime() as an alternative, but I would like to modify the existing delay time instead of creating a new one. In the code snippet provided, the delay is se ...

The command "npm install" does not automatically generate the node_modules directory, nor does it copy any .node files if the directory already exists

package.json { "name" : "xyzjs" "description" : "Sample project" "keywords": ["programming", "coding"], "version" : "1.0.0", "main": "./xyz.js" } this utilizes the binding.gyp in the current directory for project compilation, resulting in the ...

Express.js Passport.js throws an error when req.user is not defined

The middleware function below is unable to access req.user or determine if the user is logged in after they log in. I have confirmed that passport.serializeUser is successful after logging in and that req is defined when accessed from the middleware funct ...

Inquiries about ngshow and the scope concept

I have a question about using AngularJS. I have multiple sections and only want to display one at a time using <section ng-show="section6_us"> </section> and <section ng-show="section7_us"> </section>. My scope has many variables. ...

When a login attempt is unsuccessful, I am redirected to /api/auth/error using next-auth

Currently, I am utilizing next-auth version 4.18.8 on my login page for the final project of my Fullstack JS course. It's worth noting that a more recent version is being used compared to what was taught in the course (next-auth v. 3). Upon entering ...

Implementing Oauth2 with Node.js

Creating a web application using nodeJs has been my latest project. Security is crucial, so most of the functions are auth protected and I've been utilizing Oauth2 (Google, Twitter) for user authorization. Now, I need to develop an Android applicatio ...

Issue encountered while attempting to load bootstrap in NodeJS

I encountered an error while running my jasmine test case in node. The error message says that TypeError: $(...).modal is not a function. This error pertains to a modal dialog, which is essentially a bootstrap component. To address this issue, I attempted ...

Tips for preventing the appearance of two horizontal scroll bars on Firefox

Greetings, I am having an issue with double horizontal scroll bars appearing in Firefox but not in Internet Explorer. When the content exceeds a certain limit, these scroll bars show up. Can someone please advise me on how to resolve this problem? Is ther ...

The animation in Material UI does not smoothly transition with the webkit scrollbar

I've been experimenting with CSS animations in Material UI's sx property to achieve a webkit scrollbar that eases in and out. However, instead of the desired effect, the scrollbar appears and disappears instantly. Whether I define the keyframes ...

Guide to selecting a specific year on a calendar using Selenium with JavaScript

While attempting to create a Selenium test using JavaScript, I encountered an issue with filling in calendar data through a dropdown menu: const {Builder, By, Key} = require('selenium-webdriver') const test2 = async () => { let driver = awa ...