It appears that the NodeJs Express 4 async function in the model is returning before completion

I'm currently working on organizing my project by splitting the logic into different folders such as routes, views, models, and controllers.

Within a model named data (models/datamodel.js), I have implemented two methods to retrieve data for populating drop-down lists. These methods utilize sequelize for querying data asynchronously. While I have successfully used sequelize on the same page with resolve and reject callbacks, I am facing an issue in my data.js file. This file serves as a web service page that returns JSON data through a GET function. When using the object created from the dataModel and handling it with .then and .catch, the execution appears to immediately jump to the resolve callback, bypassing the intended flow. Despite multiple attempts to adjust the structures, promises, and await commands, the issue persists.

[models/dataModel.js]

'use strict';
const Sequelize = require('sequelize');

function dataModel() {

}

// Sequelize configuration
const sequelize = new Sequelize('compliance', 'username', 'password', {
    host: 'WIN-QFHT5FIC1UQ',
    dialect: 'mssql',
    operatorsAliases: false,
    requestTimeout: 300000,

    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 30000
    }
});

// Define models
var selectTo = sequelize.define('SelectTo',
    {
        to_jid: Sequelize.CHAR(100)
    }
);

var selectFrom = sequelize.define('SelectFrom',
    {
        from_jid: Sequelize.CHAR(255)
    }
);

// Asynchronous methods to get data
dataModel.prototype.getSelectTo = async function () {
    return sequelize.query('SELECT To_jid from vwTo_jid_select order by to_jid', { model: selectTo });
};

dataModel.prototype.getSelectFrom = async function () {
    return sequelize.query('SELECT from_jid from vwFrom_jid_select order by to_jid', { model: selectFrom });
};

module.exports = dataModel;

[routes/data.js]

'use strict';
var express = require('express');
var router = express.Router();
var path = require('path');
var dataModel = require('../models/dataModel.js');
var dm = new dataModel();

router.get('/:type', function (req, res) {
    switch (req.params.type) {
        case 'selectFrom':
            {
                dm.getSelectFrom().then(
                    result => {
                        res.json(result);
                    }).catch(err => {
                        res.send(err);
                    });

            };

        case 'selectTo':
            {
                dm.getSelectTo().then(
                    result => {
                        res.json(result);
                    }).catch(err => {
                        res.send(err);
                    });
            }

        default:
    }
});

module.exports = router;

Answer №1

If you're encountering issues, it may be due to your async functions not returning anything. Make sure to include return statements in your code like this:

dataModel.prototype.getSelectTo = async function () {
    // add a return statement here
    return sequelize.query('SELECT To_jid from vwTo_jid_select order by to_jid', { model: selectTo }).then(selectTo => {
        return (selectTo); //<-- Returns a valid string array
    }
    ).catch(err => {
        return (err);
    });

};
dataModel.prototype.getSelectFrom = async function () {
     // add a return statement here
     return sequelize.query('SELECT from_jid from vwFrom_jid_select order by to_jid', { model: selectFrom })
        .then(selectFrom => {
            return (selectFrom); //<-- Returns a valid string array
        }, err => {
            return (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

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...

When working with Angular 12, the target environment lacks support for dynamic import() syntax. Therefore, utilizing external type 'module' within a script is not feasible

My current issue involves using dynamic import code to bring in a js library during runtime: export class AuthService { constructor() { import('https://apis.google.com/js/platform.js').then(result => { console.log(resul ...

Issue with Braintree Integration - custom form failing to generate nonce

When I followed the code in the documentation, the nonce did not appear at the server side and I couldn't find any hidden input field for the nonce being submitted. I was only able to make it work with the drop-in form and could see the nonce on the ...

A step-by-step guide on leveraging useRef() to specifically target dynamic material-ui tabs

When attempting to upload files to a specific channel, they always end up being uploaded to the first tab or channel. I've been using useRef to try and fix this issue, but I'm not sure what exactly is missing. By "tab," I am referring to the tab ...

Creating a fresh React application to complement a pre-existing Express website

I have a unique website built with nodejs-express and ejs that consists of 5 main pages: home, events, about, developer, and gallery. All these pages are currently served using ejs. However, I am now faced with the challenge of integrating a web app create ...

Any tips for customizing the appearance of a {Switch} component from react-router-dom? I attempted to encase it in a <div> element, but it did

https://i.stack.imgur.com/4piCG.jpg https://i.stack.imgur.com/CyQH3.jpg My code attempts to modify the styling of the map component, but it seems to be influenced by the Switch component. How can I ensure that the screen fits within the 'root' ...

What's causing ng-show to malfunction in IE11 on AngularJS?

I am experiencing a strange issue with my code - ng-show works perfectly fine on Firefox, but not on IE 11. <div ng-show="isExist" class="panel panel-default"> Here is the relevant code snippet from the controller: $scope.isExist = false; if(user ...

Extract keys from the string

Is there a better way to extract keys from a string? const {Builder, By, Key, until} = require('selenium-webdriver'); ... const obj = {val: 'Key.SPACE'} if(obj.val.startsWith('Key.'))obj.val = eval(obj.val); (...).sendKeys(obj ...

When the page loads, a JavaScript function is triggered

My switchDiv function in Javascript is being unexpectedly called when the page loads. It goes through each case in the switch statement, except for the default case. Does anyone know how to solve this issue? $(document).ready(function() { $("#be-button" ...

gatsby-plugin-image compatible with macOS Catalina

Upon further investigation, I discovered that Gatsby 5 now requires node version 18 or higher. Additionally, to utilize the gatsby-plugin-image, it seems that upgrading my macOS (from OSX 10.15 Catalina to Big Sur or higher) is necessary. As I attempted ...

Bringing in a JavaScript function from a local file into a Node.js

I've been struggling with this issue for a while now and I think it's because of my misunderstanding of how files are linked in node.js. My file structure looks like this: ./main_test.html ./js_test.js ./node_test.js The main_test.html file is ...

Exploring objects as strings to retrieve data with Javascript

In a scenario where I receive an object of varying length that I do not control, I am required to extract specific data from it. The response I receive is in the form of a formatted string: { "questionId": 18196101, "externalQuestionId": "bcc38f7 ...

When using Websocket, an error message stating "Invalid frame header" will be triggered if a close message of 130 or more characters is sent

I am utilizing the ws node.js module along with html5's WebSocket. The Websocket connection is established when a user triggers an import action, and it terminates once the import is completed successfully or encounters an error. At times, the error ...

Match all routes except `/api/login/` using Regular Expressions

Currently, I am working on some authentication tasks within Express: router.post( '*', expressJwt({ secret: config.SECRET, getToken: function fromHeaderOrQuerystring(req) { if (req.cookies.sessionUniversalCook ...

Attempting to display a larger version of an image sourced from miniature versions fetched with the assistance of PHP and

I'm dealing with the challenge of displaying thumbnails fetched from a database. PHP is successfully interacting with and presenting my thumbnails. I'm currently faced with the issue of passing the id from the database to the imageID in my JavaSc ...

What could be causing the JSON.stringify() replacer function to fail?

Here is the code snippet I'm working with: http://jsfiddle.net/8tAyu/7/ var data = { "foundation": "Mozilla", "model": "box", "week": 45, "transport": { "week": 3 }, "month": 7 }; console.log(JSON.stringify(data, ...

Achieving repetitive progress bar filling determined by the variable's value

JSFiddle Here's a code snippet for an HTML progress bar that fills up when the "battle" button is clicked. I'm trying to assign a value to a variable so that the progress bar fills up and battles the monster multiple times based on that value. ...

What is the best way to add Vue dependency using CDN?

For my project which is built using Kendo, Vue, .Net, Angular and jQuery, I need to incorporate https://www.npmjs.com/package/vue2-daterange-picker. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...

A more efficient approach to creating a personalized design

After realizing the original question was unclear and wouldn't solve my problem, I have decided to edit it and create a new one. For my project, I require a customized layout where users can move, resize, add, or remove each box according to their pr ...

Swap out the image for a div element if the image is not found

Is there a way to accurately display an image if it's available, and use a div as a replacement if the image is not present? // How can I determine `imageExists` without encountering cross-origin issues? (imageExists) ? (<img class="avatar-img" sr ...