Unable to add MySQL results to the array

This is the code I am working on:

var nbu = req.body.nbu;
var inv=[];
db.query(
  "SELECT * FROM `invoice_ska` WHERE nm_client =?",
  nbu,
  (err, results) => {
    if (err) throw err;
    inv.push(results);
  }
);
console.log(inv);//this just []
});

I am facing an issue where I cannot console.log(myArr) and I am not sure why.

Answer №1

Dealing with asynchronous problems can be tricky, but fear not! You can learn about handling asynchronous JavaScript in a very comprehensive way through this fantastic guide on MDN.

In your specific situation, remember to use console.log inside the query callback block because the database query operates asynchronously. This means you must wait for the query to complete and return the data before proceeding.

var user = req.body.user;
var results=[];

db.query(
  "SELECT * FROM `user_data` WHERE username =?",
  user,
  (err, data) => {
    if (err) throw err;
    results.push(data);
    console.log(results);
  }
);

Answer №2

To achieve this, make sure to implement async await in your code so that it waits for the promise to resolve before executing your logic.

const doSomething = async (req, res) => {
var input = req.body.input;
var resultsArr= [];
let data = await database.query(
    "SELECT * FROM `table_name` WHERE column_name =?", input
);
if (data) {
    resultsArr.push(data);
}
console.log(resultsArr);//this will output an empty array }

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 is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

Choose the specific Element by its dynamicID in JQuery

Just starting out with Jquery and I have a specific task in mind. In my HTML page, I have elements with IDs generated by concatenating a string variable. My goal is to use JQuery to select the element with this dynamically generated ID. See below for more ...

What is the best method for displaying multiple slices within an SVG circle?

I'm currently working on a project involving a reactJS application. The goal is to display an svg circle that, when clicked, divides into n equal slices. I have successfully generated the individual slices with the following code: renderSlices = () ...

Customize the DOM with tailwind CSS in a Vanilla JavaScript project

I am attempting to hide the "mark as complete" button and replace it with a "completed" button by switching the classes from "hidden" to "completed" and vice versa. However, when I use an event listener to manipulate the DOM with the code provided below, t ...

Tips for dynamically expanding the interface or type of an object in TypeScript

Currently, I am exploring the integration of PayPal's Glamorous CSS-in-JS library into a boilerplate project that also utilizes TypeScript. Glamorous provides a way to incorporate props into an element as shown below: const Section = glamorous.secti ...

Generating multiple div elements within an AJAX iteration

Currently, I am retrieving data from the server side using AJAX. My goal is to populate data from a list of objects into divs but I am facing an issue where I cannot create the div while inside the foreach loop. $(document).ready(function () { var ...

What is the best way to distinguish between two POST requests in Express.js?

I am currently working with two different forms within a single inven.ejs file: The first form is for simple description: ///inven.ejs <form method="POST" value="inven"> <div id="some-form" style="display: none;"> <table> ...

Ways to automatically close browser tab upon successful submission of a form

I have an old file that has been updated. One of the requirements for this file/project modification is to have the current browser window close when the user clicks OK to submit the form. I am curious if this can be done using plain/vanilla JavaScript? ...

Tips for adjusting the width of a Facebook embedded video within its container using ReactPlayer

Has anyone encountered issues with adding an embedded video to a NextJS app using ReactPlayer and Facebook videos? It seems that Facebook does not support the width="100%" attribute, as it always snaps back to 500px. Interestingly, this works wel ...

Node and Express Fundamentals: Delivering Static Resources

const express = require('express'); const app = express(); app.use(express.static('public')); I've been attempting to complete the "Basic Node and Express: Serve Static Assets" challenge on freecodecamp, but it keeps showing as " ...

I keep encountering an issue with npm where it is unable to identify the executable to run whenever I launch VS Code and attempt to use Cypress

Whenever I open Visual Studio Code and try to run 'npx open cypress', I keep encountering this message in my terminal: npm ERR! could not determine executable to run Oddly enough, running 'npx cypress -v' provides version details, so ...

Introduce an additional parameter to the Prestashop Cart entity

After setting up a radiobox "stock_action" in the Cart, I need to send its value to the Cart object for additional order costs. In the Cart Override, the $stock_action variable has been added: public $stock_action; /** * @see ObjectModel::$defi ...

IE is failing to display the textarea, but it is successfully getting submitted

I've written a function in jQuery and JavaScript that generates a form element: createEmail: function(title){ var $emailForm = $('<form>',{action: 'sendEmail.php', id: 'emailForm'}); var $table = $( ...

Generate fresh JavaScript objects with customized properties

My goal is to use Javascript and JQuery to automatically create a new object with properties provided by the user when they fill out an HTML form. I have a constructor named "object" for this purpose. function object (prop1, prop2, prop3) { this.p ...

Utilizing MySQL to match two conditions across multiple tables

My current mysql query looks like this: $query5 = mysql_query("SELECT * FROM `pages` WHERE (`id`='$switch' AND `rand`='$randID' AND `email`!='".$_SESSION['user']."') "); Additionally, I have another query that re ...

What is the purpose of using square brackets in the angular.module() function in AngularJS?

const myapp=angular.module('myApp',[]); As someone venturing into the realm of angularjs, I have a question. What is the significance of using [] in angular.module()? If anyone could shed some light on this, it would be greatly appreciated. ...

"Learn how to convert basic input fields into user-friendly Bootstrap input groups using the power of jQuery

Is there a way to use jQuery to convert my basic input field into a bootstrap input-group like the one shown below? This is how I created the input: <div class='input-group date' id='ff'> <input type='text' class= ...

Design a collection of image icons to use as a toolbar in a web

I am in the process of creating a basic online application that allows users to select images from a toolbar (or storage box) and drag them onto a canvas. I am relatively new to web development but have figured out the drag and drop functionality. Right no ...

Error Found: Syntax Error - 'if' statement not recognized

if (fname == null || fname == "") { Receiving an error message "uncaught syntax error:unexpected token if in line 13". The error indicates "SyntaxError: missing variable name" when using Javascript lint function validateRegistration() { var emailReg ...

Obtain the current status of a Stripe charge made with a specific source token using Node.js and

Imagine this scenario: a user submits a credit card token to my server for a purchase, and I save the token in their cart. However, just as I am about to store the charge id from the success response, my server crashes. The charge has been processed, but ...