In node.js, create a variable that stores the result of an SQL query to count the number of rows in

Within my node.js javascript program, I am working with a (postgres sql) table. My objective is to determine the number of rows in the table and store this value in a variable (n) for further use in the code.

In response to feedback, I have included more surrounding code and attempted to implement the initial solution provided:

db_connnection.query(display_query).then(result => {
        io.to(roomId).emit('room-display-update', result.rows);
      
       const queryFunction = async (db_connnection) => {
            var n = await db_connnection.query("SELECT COUNT(*) as total FROM waypoint", function(err,Result) {
                   return parseInt(Result.total);
            });
            console.log("There are", n, "inside queryfunction"); 
            return n
        };
        
        var nn = queryFunction(db_connnection);
        console.log("There are", nn, "outside queryfunction"); 

Despite trying various methods, such as the one above, I continue to face challenges due to my limited coding knowledge. Errors range from type errors to 'undefined' or 'promise' returns.

How can I ensure that the variable n actually holds the value 2 (in this particular scenario)?

The problematic snippet now appears like so, accompanied by corresponding console.log errors:

        var count_query = "SELECT COUNT(*) as total FROM waypoint" 
        async function Countit(count_query) {
            const ioResult = await db_connnection.query(count_query).then(async (result) => { 
            console.log("There are", result.total, "inside function")
            return parseInt(result.total);
            })
        console.log("There are", ioResult.total, "inside ioResult")
        };
        var nn = Countit(count_query);
        console.log("There are", nn, "outside function");

Answer №1

Executing database calls asynchronously is crucial as the data retrieval process may not have completed when you attempt to log the value. Consider using async/await or promise/resolve syntax to handle this asynchronous behavior effectively.

const fetchData = async (database_connection) => {
      var result = await database_connection.query("SELECT COUNT(*) as total FROM maintable", function(err, data) {
                return parseInt(data.total);
        });
        console.log("Data Result:", result);
        return result;
};

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 causes the variation in size between the next/image and img HTML elements?

Two Images, Different Sizes! https://i.sstatic.net/vpoNG.jpg There seems to be a discrepancy in size between the image rendered by the next/img component and the one displayed using the img element. Interestingly, they both use the same image source and ar ...

Node.js/Firebase function to delete an item from a JSON object and update the existing items

I'm currently facing a challenge with updating a JSON file in Firebase after deleting an item using the .delete() function. Here is the original JSON data before deletion: "data": [ { "position": "3", ...

Send multiple input groups using Ajax POST requests

I need help setting up a form with 4 groups of checkboxes for refining search results. My goal is to send an array for each checkbox group that contains the IDs of the currently selected checkboxes. $.ajax({ url: "/stay_in_belfast/accommodation", t ...

Retrieving MongoDB Query Data in Node API - What is the best way to send the mongoDB query results back to the

As a newcomer to JavaScript, I decided to challenge myself by diving into Node API development, specifically experimenting with querying my MongoDB. In my API's index.js script utilizing the 'express' module, I aim to return query results in ...

What is the best way to fetch the highest ID from the main table, then use it to add a new entry in the main table and multiple entries in the child

After pressing the add button, the entered data will be transferred to the child table, while the existing data will be stored in the master table. Here is a visual representation of the layout: https://i.sstatic.net/SdHSX.png Event handler for saving b ...

Submitting jQuery Ajax forms multiple times using the POST method

After trying various solutions for this issue, none seem to effectively address my problem. Here are some examples: $("form#sending-notice-form").unbind('submit').bind('submit', function (e) { e.preventDefault(); .. }); While ...

Using Angular Material - How can we link a personalized directive attribute to the md-list-item component?

When trying to connect a custom directive to items in an ng-repeat list generated with md-list/md-list-items, I encountered a challenge due to the way angular material organizes the md-list-item element when it's rendered in the DOM. This includes nes ...

Reverting button highlighting when another button is selected in Web development using CSS and Bootstrap

On my signup page, I have two buttons that control the display of corresponding containers. However, I encountered an issue where clicking a button changes its background color and keeps it changed even after selecting the other button. If I click the same ...

Is there a way to adjust the brightness of specific sections within an image using html, css, and js?

I am working on a project where I have an image with tags underneath that correspond to different parts of the image. For example, if the image is of a dog, one of the tags could be 'nose', indicating the portion of the image around the dog' ...

interval-based animation

I'm trying to create a simple animation using setInterval in JavaScript. The goal is to make an image move from left to right. HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"& ...

Issues with jQuery tabs functionality in Magento are causing malfunction

I've been experimenting with creating a tab system in Magento using a specific plugin, which you can find here: However, after completing the setup and including the necessary HTML, CSS & javascript, the tabs are not functioning as expected. Inst ...

Using Wordpress to store web page URLs as variables

I have been working on a Wordpress function that is supposed to fetch the URL of the current page that a visitor is browsing. Here's what I have so far: function retrieve_page_url() { $pageurl = "http://".$_SERVER['HTTP_HOST'].$_SERVER[&apo ...

Error: The module you are trying to import from the package is not found. Please check the package path and make sure that

I encountered an issue when trying to compile a code in Reactjs. As a beginner in Reactjs, I'm struggling with this. Module not found: Error: Package path ./cjs/react.development is not exported from package /Users/mansi/letsgrowmore/to-do-list/my-rea ...

use the useState hook to update an array of objects by adding a new object

Currently, I am in the process of developing a straightforward order list web application using react hooks. Within this app, there is an orders state that gets updated whenever a user clicks on a product image in the shopping panel. When this action occur ...

Using AJAX in PHP to submit checkbox values in a form without reloading the page

Recently, I delved into learning ajax and found it to be truly amazing and a major time-saver. However, I encountered a roadblock when attempting to send form data without having the page reload. Here is an excerpt of my HTML code. <form id="form ...

Creating an array of choices using jQuery: A step-by-step guide

In a jQuery solution I found on Stack Overflow, there was code used to show a specific div block only when certain menu options are selected. While I'm not well-versed in jQuery, I believe the $.viewMap block could be optimized to avoid repeating part ...

Insert a fresh item to the end of the scrollable container

My goal is to dynamically add a div to the bottom of another div by using a JavaScript button click event. However, I have encountered an issue where once the outer container reaches its maximum height, the list no longer scrolls to the bottom after adding ...

Steps for launching an HTML+CSS+JavaScript project on an Android Emulator

My current project is built using HTML 5, CSS3, and JavaScript. It runs perfectly on an internet browser when accessed either through localhost or a server. Now, I am looking to run my project on an Android Emulator. I have tried accessing it using http:/ ...

Tips for Displaying Dynamic Variables in PHP

Thank you for taking the time to try and assist me with my issue! The problem I am facing involves displaying a variable on my webpage using PHP. This variable is constantly updating every second or so, and I want it to update on the page in real-time as ...

The challenge of Cross-Origin Resource Sharing with AjaxSubmit compared to a traditional Ajax request

My dilemma involves two applications interacting on Google's App Engine, each operating within its own domain. To enable communication between them, I have successfully implemented CORS in Python using the following code: self.response.headers.add_he ...