JavaScript: a function being exported fails to return either true or false

In a separate file, there is a function that checks for the existence of an admin in the database. If no admin is found, it creates one. The function should return true if an admin is present by the end, and false if not.

/*AdminUser.js*/
const Admin = require('../models/admin');
const mongoose = require('mongoose');

module.exports = {
validate: function() {
    Admin.getAdminByRealID("1212", (error, admin) => {
        if (admin) {
            console.log("Main admin is Booted");
            return true;
        } else {
            console.log("Booting main admin");
            let newAdmin = new Admin({
                ID: "1212",
                account: {
                    username: "Admin",
                    password: "1212",
                    token: "Admin"
                },
                name: {
                    first: "Admin",
                    last: "Delta"
                },
                communication: {
                    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3357565f475273564b525e435f561d-505e">[email protected]</a>",
                    phone: "1212"
                }
            });
            Admin.addAdmin(newAdmin, (error, admin) => {
                if (error) {
                    console.log("Admin reboot failed");
                    return false;
                } else {
                    console.log("Admin have been initialized");
                    return true;
                }
            });
        }
    });
}
}

In the main application, the following code is used:

if (AdminUser.validate()) {
     app.listen(port, () => {
     console.log('Server started on port: ' + port);
     });
} else {
     console.log('Fail to run Server');
     process.exit();
}

The .validate function is returning an 'undefined' object causing the server to fail to start. Can someone clarify why the return value is not true or false?

The .validate function does print "Main admin is booted" so I assume it returns true afterwards.

Using app = express();

Answer №1

AdminUser.validate() function actually returns undefined. Upon inspecting the function's body, it becomes evident that the results are obtained through callbacks from Admin.addAdmin and Admin.getAdminByRealID. In order to handle these results outside of the function, it's recommended to include a callback parameter in your validate method. This methodology aligns with the standard practice of node asynchronous programming (although there are more modern techniques such as Promises and await).

const Admin = require('../models/admin');
const mongoose = require('mongoose');

module.exports = {
validate: function(done) {
    Admin.getAdminByRealID("1212", (error, admin) => {
        if (admin) {
            console.log("Main admin is Booted");
            done(true);
        } else {
            console.log("Booting main admin");
            let newAdmin = new Admin({
                ID: "1212",
                account: {
                    username: "Admin",
                    password: "1212",
                    token: "Admin"
                },
                name: {
                    first: "Admin",
                    last: "Delta"
                },
                communication: {
                    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d494841594c6d48554c405d4148034e4240">[email protected]</a>",
                    phone: "1212"
                }
            });
            Admin.addAdmin(newAdmin, (error, admin) => {
                if (error) {
                    console.log("Admin reboot failed");
                    done(false);
                } else {
                    console.log("Admin have been initialized");
                    done(true);
                }
            });
        }
    });
}
}

Here's how you would call it:

AdminUser.validate((ok)=> {
  if(ok){
    app.listen(port, () => {
      console.log('Server started on port: ' + port);
    });
  } else {
    console.log('Fail to run Server');
    process.exit(1);
  }
});

Answer №2

It's important to understand that your validate() function operates asynchronously. This means that it doesn't return a value immediately upon execution because it carries out operations like querying the database before providing a result.

As a result, you can't simply call validate() in your main app and expect an instantaneous outcome. Instead, you need to structure your code so that your app can continue running once validate() completes its tasks. One common approach is to utilize callbacks, which involves defining a callback function like the following:

validate: function(callback) {
    ...
    if (error) {
        console.log("Admin reboot failed");
        callback(false);
    } else {
        console.log("Admin has been initialized");
        callback(true);
    }
    ...
}

In your main app, you can then use the callback in the following manner:

AdminUser.validate(function afterValidation(isValid) {
    if (isValid) {
        app.listen(port, () => {
            console.log('Server started on port: ' + port);
        });
    } else {
        console.log('Failed to start server');
        process.exit();
    }
});

The key concept is to provide your asynchronous function with instructions to follow upon completion by passing a callback function for execution.

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

What are the steps to utilize the Angular package within NodeJS and Express?

After installing the Angular package through npm install for my Express project, I am feeling a bit lost on how to actually use it. Can someone explain how to properly implement Angular after installing it this way? Alternatively, is the only way to util ...

What is the best way to implement sorting in a table using react virtualized?

I've been working on implementing sorting in my project using the table sorting demo available on Github. Here is the code I'm using: import React from 'react'; import PropTypes from 'prop-types'; import { Table, Column, Sor ...

Steps for implementing target='_blank' on a <Link> tag with more than just an <a> element inside

I'm facing an issue where I need to open a new browser tab and redirect to a specific URL when a button is clicked. The problem arises when using an element other than an anchor tag inside the Next's <Link> element, as it seems to ignore th ...

Tips for placing modal box in the exact desired position upon loading

I've been searching for a solution on how to dynamically calculate the position of each image loaded in a Twitter modal box and place the box underneath a custom toolbar element I have created. The situation is depicted in the image. The height of the ...

Breaking down a number using JavaScript

Similar Question: JavaScript Method for Separating Thousands I'm looking to find a way to separate numbers by a thousand using JavaScript. For example, I would like to turn "1243234" into "1 243 234", or "1000" into "1 000" and so on. (sorry for ...

Guide on utilizing the reduce method with objects

I am attempting to use the reduce method on an object to create an HTML list const dropdownTemplate = (data) => { console.log(data); // no data displayed return ` <li class="dropdown__item" data-value="${data.value}"><span class="dropdown__i ...

How can I match dates in order to run the following code?

If Purchase Date is after 31/Mar/xxxx it should not calculate elap_yend, rem_days, depre_cur, cur_wdv. Also I have to calculate GST with some options that is if SGST and CGST are chosen, I should not calculate IGST else if IGST selected or marked it shoul ...

What is the best way to maintain a socket.io ID while navigating through dynamic HTML files?

Utilizing express and node for server hosting, socket io is employed to track users by saving their unique socket.id. There are two pages in the webapp - a login page and a content page. app.get("/", function(req, res) { res.sendFile(__dirname + "/log ...

What is the reason for not being able to locate the controller of the necessary directive within AngularJS?

A couple of angularjs directives were written, with one being nested inside the other. Here are the scripts for the directives: module.directive('foo', [ '$log', function($log) { return { restrict: 'E', r ...

Node JS and Express integration for Sweet Alert confirmation

I currently have a Node JS/Express application with .EJS templates in which I have implemented code to display standard 'Are You Sure' messages before making changes to records. The functionality for editing and deleting records is functioning co ...

Utilize Node.js to efficiently send emails to a group of subscribed clients

I have a Node.js website on my local system that sends email notifications to users about trending articles or posts. Here's how my code works: app.get('/:articlename', (req, res)=>{ conn.query(`SELECT views,isAlreadySent FROM article_ta ...

Implementing parallel HTTP requests with a dynamic number of requests using RxJs

Currently, I am in the process of building a Node.js API that utilizes Express. As part of this project, I am incorporating the node-rest-client module to handle HTTP requests. One of the key API endpoints that needs to be developed is /api/v1/users/:user ...

What is the quickest way to display data immediately after submitting a form using ajax?

Is there a way to display data instantly after submitting a form via AJAX and saving it through a controller function? I want to be able to view the saved data on the same page without having to refresh it: <span class=" store_comment_like " data-com ...

Stopping a build programmatically in Next.js involves implementing specific steps that aim to halt

Is there a method to programmatically halt the execution of npm run build in Next.js when a specific Error occurs within the getStaticProps function? Simply throwing an Error does not seem to stop the build process. ...

Why isn't the table in the select query updating after an insert query is executed in Express?

Seeking assistance! Currently, I am delving into express and typescript. I have encountered an issue where the table from a select query does not update after an insert query when rendering a view. Strangely, the data in the table remains unchanged (showin ...

Using the class attribute for Pagedown instead of the id keyword

I am utilizing Pagedown, which necessitates giving the id wmd-input to a textarea. This requirement is outlined in Markdown.Editor.js as follows: function PanelCollection(postfix) { this.buttonBar = doc.getElementById("wmd-button-bar" + postfix); ...

A step-by-step guide on showcasing the content from a textfield onto a dynamic column chart

How can I show the value from a text field in a column chart? I found the code for the chart on this website(). I tried using the code below, but nothing happens. Can someone please assist me? <script> window.onload = function () { ...

Choosing the fourth cell in every row of a table and converting the information

Currently, I am working on a function that is supposed to take the fourth column in each row of a specific table, manipulate the data using a function, and return different data for the cell. This function takes an integer representing total minutes as i ...

Issue with karma-ng-html2js-preprocessor failing to generate modules

Struggling to configure the karma-ng-html2js-preprocessor. While Karma has been successfully detecting all my JavaScript files, it's having trouble generating a module from the HTML preprocessor. Take a look at my options object below. I've spec ...

The onKeyUp event in Material-UI components does not seem to be functioning as

I am experiencing an issue with a material-ui component Grid where the onKeyUp event does not seem to be triggering as expected. Here is the code snippet: <Grid item xs={12} onKeyUp={handleClickOnKeyUp} sx={{cursor: "pointer"}} onClick= {ha ...