The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js?

In queries.js:

const rsClient = require('./client.js');

const query = {
    one: 'SELECT * FROM my.db'
}

module.exports = {
    rsProdRecs: (req, res) => {
         rsClient.query(query.one)
            .then(res => {
                return res;
            })
            .catch(err => console.log(err));
    }
};

In routes.js

var express = require('express');
var router = express.Router();
var queries = require('../queries');

router.get('/', function(req, res, next) {
  const data = queries.rsProdRecs();
  console.log(data)
  res.send(data);
});

module.exports = router;

Answer №1

There are a few issues in the provided code snippet that need to be addressed. One of the main concerns is ensuring that the promise returned by rsProdRecs is properly handled. Additionally, the usage of then and catch blocks needs to be optimized for better error handling. Below is an example of how you can refactor your code to address these issues:

module.exports = {
    rsProdRecs: (req, res) => {
        return rsClient.query(query.one);
    }
};

To consume the Promise-returning method effectively in your route, consider the following implementation:

router.get('/', function (req, res, next) {
    queries.rsProdRecs()
        .then((data) => {
            console.log(data);
            res.send(data);
        })
        .catch((err) => {
            console.log(err);
            res.status(500); // Proper error response handling
        });

});

You could also utilize async/await syntax for better readability and concise code:

router.get('/', async function (req, res, next) {
    try {
        const data = await queries.rsProdRecs();
        console.log(data);
        res.send(data);
    } catch (e) {
        console.log(err);
        res.status(500); // Handle errors appropriately
    }
});

Answer №2

Have you attempted to include the return statement?

rsProdRecs: (req, res) => {
         return rsClient.query(query.one)
            .then(res => {
                return res;
            })
            .catch(err => console.log(err));
    }

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

Returning Props in Dynamic Components with Vue 3

Exploring the capabilities of Vue3's Dynamic Component <component>, I am currently working with this setup: Component 1: <template> <div> <h1> Name Input: </h2> <Input :model="props.name" /> ...

The process of combining identical data values within an array of objects

Can anyone help me with merging arrays in JavaScript? Here is an example array: [{ "team": team1, "groupname": "group1", "emp-data": [{ "id": 1, "name": "name1", }], }, { "team": team1, "groupname": "group1", " ...

Unable to locate module with React and Material-UI integration

When attempting to implement a Material button in my React app, I encountered the following error: Failed to compile. ./node_modules/@material-ui/core/styles/index.js Module not found: Can't resolve '/Users/hugovillalobos/Documents/Code/Lumiere ...

Using custom modules with cyclic dependencies is not functional

I have created two custom npm modules with the scope name "company". The structure of my modules a and b is as follows: module @company/a : f1(x){moduleB.f2(x);} f2(x){...} module.exports = {f1, f2}; // cyclic dependency require var moduleB = requi ...

Having Trouble Locating UiAutomator2 in Appium for Android with Python?

I keep encountering an error even though I have confirmed that uiautomator2 is installed correctly. It's puzzling to me, perhaps it has something to do with my desired capabilities? In the past, I've used cloud Appium without issues, but this tim ...

Error: Unable to access 'price' property of undefined - Next.js version 14.0.1

I'm encountering an issue with Next.js where my code is not working as expected. Interestingly, the same code works perfectly fine in other templates. let subTotal = 0 if (selectedProducts?.length) { for (let id of selectedProducts) { ...

What steps can be taken to properly display dateTime values in a data table when working with JavaScript (VueJS) and PHP (Laravel)?

I am facing an issue where I am unable to save user inputted date-time values from a modal into a data table. Despite receiving a success message, the dateTime values are not being added to the table. My payload only displays the state and approval fields ...

Encountering an issue when trying to execute the npm start command in the Windows 10 command prompt

Need assistance with a React error. I encounter this screen when attempting to run the command npm start after creating a new React project. ...

I keep encountering the following issue: "It seems that the file requested at /images/crown.png is not recognized as a valid image, as it was received as text/html; charset=utf-8."

I encountered an issue while utilizing Next.js. Here is the code snippet where the error occurred: import React from "react"; import { Container, Col, Row } from "react-bootstrap"; import Image from "next/image"; export defaul ...

"The Jade templating engine in Express no longer retains relative directory paths within the href

In my Express web app, I have a Jade view with a specific element. When accessing the current URL http://localhost:3000/location, the page displays a list of locations, each represented by an ID in a hyperlink like: http://localhost:3000/location/1 http: ...

How to Retrieve the Access Token from Instagram using Angular 2/4/5 API

I have integrated Instagram authentication into my Angular 2 project using the following steps: Begin by registering an Instagram Client and adding a sandbox user (as a prerequisite) Within signup.html, include the following code snippet: <button t ...

Using Ajax and PHP to upload an image

I'm looking to implement an image upload feature triggered by a button click with the id of #myid.save. Below is the code I have so far: HTML Code: <canvas id="cnv" width="500" height="100"></canvas> <input id="myid_save" type="submit ...

setting a variable with data retrieved from an AJAX call using jQuery

Here's a snippet of jquery code that I'm working with: var example = "example"; $.ajax({ url: root + "/servletPath", type: "GET", success: function (response) { alert(response); // displays the correct value example ...

Ways to extract information from PayFast

One issue I'm facing with my online store is that although PayFast does call my notify_url, it appears that no data is being posted. Below are the codes I've been using: Code for purchasing: <button id="cCart" type="submit" class="bt ...

In what way can the jQuery .each() function make use of the index as a variable?

Consider the jQuery .each() function, which comes with a useful feature. For example: $('.element').each(function(index){ console.log(index); }); Here, you can access the index of the currently selected element using the "index" variable. ...

Guide to successfully integrate MathJax into your React application

I developed an application using HTML that successfully rendered MathJax equations through a script tag. However, after transitioning to React, the MathJax equations are no longer appearing. I have tried adding the MathJax script (shown below) in the comp ...

The CORS policy has blocked the 'Access-Control-Allow-Origin' header

My expertise lies in creating API, BackEnd, and Frontend websites. For the API, I utilize Express, while for the BackEnd - FrontEnd, I rely on ReactJs. During local testing, everything functions as expected. However, upon deployment to the server, error ...

How can the required flag be integrated with rules validation in react-hook-form and material-ui (mui) for inputs?

Currently, I have implemented react-hook-forms for handling form functionality and validation in our application. On the other hand, we are utilizing MUI/Material-UI as our component library. One issue that arises is that MUI automatically adds a * to inpu ...

The value of the jQuery data on click event handler becomes 'undefined' when used within an AJAX handler

When I click on the Positive or Negative buttons, a jQuery event handler function is triggered. Each button passes different data objects to the handler. However, within the AJAX POST handler, I am unable to access the data from the click event. $('# ...

What is the best way to deploy a nodejs expressjs application to a server?

I have successfully developed a nodejs and express application that works perfectly on my localhost. To start the application, I simply run the command npm start or node index.js. Recently, I uploaded all the necessary files, including node_modules, to a ...