Javascript not waiting for function return when using console.log statement

I am facing an issue where I need to set a variable x to the result obtained from the showData function. Below is my code snippet:

app.post("/view/show", (req,res) => {
    let x = showData(req.body.custmerName);
    console.log(x);
}

Here's how the showData function looks like:

const showData = (custName) => {
    const customer = mongoose.model(custName ,collectionSchema,custName);
    customer.find( (error,data) => {
        if (error){
            console.log(error);
        }else{
            return data;  
        }
    });
}

Despite successfully fetching data from the database and logging it using console.log(data), when I tried to log the value of x, it displayed undefined. This seems to happen because the console.log(x) does not wait for the execution of showData() due to JavaScript's synchronous nature. What can I do to ensure that the value returned by the function is properly logged instead of being shown as undefined?

Answer №1

Utilizing async/await or callbacks is the recommended approach when dealing with asynchronous functions.

app.post("/view/show", (req,res) => {
  showData(req.body.custmerName, (err, res) => {
    const x = res;
    console.log(x);
  });
});

const showData = (custName, callback) => {
  const customer = mongoose.model(custName ,collectionSchema,custName);
  customer.find(callback);
}

Answer №2

I am not familiar with using Mongoose, but upon reviewing the documentation, it appears that there is no direct callback function available for the find method.

You can try passing an empty query object as well:

customer.find({}, (error,data) => {
    if (error) {
        console.log(error);
    } else {
        return data;  
    }
});

According to the documentation:

// find all documents
await MyModel.find({});

// find all documents named john and at least 18
await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();

// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();

// passing options
await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();

Answer №3

In order to accomplish this task, you will require an asynchronous function. Follow these steps:

app.post("/view/show", async(req,res) => {
    let display = await fetchCustomerData(req.body.custmerName);
    console.log(display);
}

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

Tips for converting NULL% to 0%

When running my calculatePercents() method, I am receiving NULL% instead of 0%. https://i.sstatic.net/NSbls.png Upon checking my console.log, I noticed that the values being printed are shown as NULL. https://i.sstatic.net/A7Jlk.png calculatePercents() ...

javascript The final position achieved through requestAnimationFrame is never precise

let pf = document.querySelectorAll('.pf'); for (let i of pf) { Object.assign(i.style, { left: '400px' }) } function shiftLetters() { let start = performance.now(); let dist = -400; let dur = 500; const logoAnimate = ( ...

A Webpage that is permanently open, with no option to close it. The only option is to watch the video in

Currently, I am designing web pages for artists to showcase their work in an upcoming exhibition. The pages are ready, but now the artists are requesting that each piece be accompanied by a laptop displaying a single webpage with a video providing informat ...

The filter function in Node.js is failing to correctly sort jobs based on their category IDs

Currently, I am working on a project using node js with express and mongoDB. In this project, I have created two schemas: one is called jobmodel and the other is jobTypemodel. Everything seems to be functioning properly with the routes, controllers, and al ...

An issue arose when trying to display React components within an Angular application

Attempting to incorporate React components into an Angular 7 application has been a challenge for me. While I have successfully rendered simple React components, I encountered the following error message (displayed in the browser console) when attempting t ...

Using Choices.js to inject live data into the select dropdown options

I am currently utilizing Choices.js for multi-select functionality and incorporating a select with a search box. Even though I am using Angular.js to populate the data, it does not appear to be functioning correctly. Is there anyone who can assist me in dy ...

Click to execute instantly without encountering any errors

I'm working with a modal in React JS and I want to trigger a function when the modal opens. I currently have a button function that is functioning correctly using the following code: <button onClick={functionExample("stringParam", true)} ...

What is the best way to retrieve data from the server using (Express) after the form data has been submitted (React) and successfully processed?

I am in the process of developing a search-based web application for League of Legends, a popular MOBA game. This app allows users to input their summoner's name and retrieve general information using the game's third-party API. While I have suc ...

Error encountered when attempting to remove child: the user ID of the product must be specified and cannot be null

I'm encountering an issue with Sequelize while trying to remove a product associated with a user. Sequelize is indicating that product.userId cannot be null: { "name": "SequelizeValidationError", "errors": [ ...

How can we retrieve jwt user data in a vulnerable endpoint using express-jwt in a nodejs environment?

While utilizing express-jwt to secure my endpoints, I have come across a situation where I need an unprotected endpoint to display additional information for logged-in users. Is there a method to access user information in an unprotected endpoint? The cod ...

Having trouble importing the d3-geo package into a Node.js TypeScript project

Seeking a way to test the inclusion of specific latitude and longitude coordinates within different GeoJSON Features using code. When attempting this with: import d3 from 'd3-geo'; // or: import * as d3 from 'd3-geo' // no difference ...

Mastering preventBack() Functionality - A Foolproof Method to Eliminate a Div on Back

This unique code prevents the page from going back when using the back button: <script type = "text/javascript" > function stopGoingBack(){window.history.forward();} setTimeout("stopGoingBack()", 0); window.onunload=function(){null}; ...

The JavaScript function exclusively reveals the final element, which is Three.js

I'm currently working on a fence generator function using Three.js, but for some reason, my function is only returning the last fence created. It's really puzzling to me... function createFence(nb){ var i; var position = -5; var loadingMan ...

Having trouble with AES decryption on my nodeJS/ExpressJS server backend

Looking to decipher data post retrieval from mongoDb. The retrieved data comprises encrypted and unencrypted sections. app.get("/receive", async (req, res) => { try { const data = await UploadData.find(); const decryptedData = data. ...

Guide to automatically compressing images during the file upload process

Is there a way to automatically compress images larger than 4MB to less than 1MB before uploading them in AngularJS? Any suggestions on how to achieve this? Here is the sample file: JSFIDDLE var myApp = angular.module('myApp', []); myApp.dir ...

Updating the style sheet of a selected menu item on an ASP.NET master page

I created an asp.net master page with a menu setup like this: <menu id="menu"> <nav id="main_nav"> <ul id="menu-primary"> <li ><a href="./">Home</a></li> <li><a href="staff.aspx"& ...

JavaScript - Fetch POST request is being terminated - Windows Error 10053

Seeking help for my JavaScript project course. The function is aborting during the fetch process. Chrome is the browser being used to test the project. It was intermittently "sending" before, but now it's not working at all. Had to run the app in Chro ...

Sending input values from textboxes to the Controller

I currently have the following code snippets: Home Controller: public IActionResult Index() { return View(); } public ActionResult Transfer() { string path = @Url.Content(webRootPath + "\\SampleData\\TruckDtrSource.json&q ...

The animation feature on the slideshow is dysfunctional

For this Vue component, I attempted to create a slideshow. The process is as follows: 1) Creating an array of all image sources to be included (array: pictures) 2) Initializing a variable(Count) to 0, starting from the beginning. 3) Adding v-bind:src=" ...

CSS/SCSS/JS: Adjusting header height dynamically while keeping it fixed at the

Check out my Codepen demo here: https://codepen.io/nickfindley/pen/dJqMQW I am seeking to replicate the current behavior of the page without specifying a fixed height for the header. The goal is to make the header adjust dynamically based on the content, ...