Every time I use my NodeJS MySQL Query function, the results I get are never

Working on a new gaming project involving MySQL for multiplayer functionality. Issue arises when requesting specific queries, where the system retrieves incorrect data or results from previous queries.

dat("SELECT * FROM server1;"); 

Misdirected queries returning unintended highscore table data instead of the requested server1 content.

dat("SELECT * FROM playernames;");

This auto-saving query function executes previously initialized queries each time it's used.

Attempted to resolve with online resources and Promise method but struggled due to unfamiliarity with handling Promises; resorting to async and await methods.

async function dat(Befehl) {
  // Function code here
}

Expected response using the function

let x = await dat("SELECT * FROM server1;");

In theory:

Player1Cards = "Cards"
Player1CardsColour = "Colour";
Player2Cards = "Cards";
Player2CardsColour = "Colour";
Player1Name = "Name"
Player2Name = "Name"

However, actual result provides the highscore table data repeatedly until multiple function calls return correct data after 3-6 attempts.

Also included are additional functions utilizing the query:

// Other functions

Debugging function clearing all servers:

function AlleFreigeben()
{
  // Code to clear servers
}

Login functionality integrated within the application:

async function prelogin()
{

  // Login code here
}

User registration feature:

async function register()
{
  // Registration logic
}

Initiating game start sequence:

async function UnoStartHM()
{
  // Game initialization process
}

Unfortunately, certain functions like Abfrage() experience issues in contrast to manual MySQL query execution via console.

async function Abfrage()
{
  // Query function struggling with database interaction
}

Answer №1

The problem lies in the variable temp being assigned a value from a query that is executed before receiving a response from the database. I strongly recommend delving into the world of Promises for a solution.

Here's a code snippet that demonstrates the correct way to handle asynchronous operations using Promises. Pay close attention to where the resolve() and reject() functions are invoked.

async function connect() {
  return new Promise((resolve, reject) => {
    // Assuming con is defined elsewhere.
    con.connect(function(err) {
      if (err) return reject(err);
      console.log("MySQL: Connected to localhost!");
      con.query("USE abschlussprojekt;", function (err, result) {
        if (err) return reject(err);
        console.log(result);
        return resolve();
      });
    });
  })
}

async function query(command) {
  return new Promise((resolve, reject) => {
    con.query(command, function (err, result) {
      if (err) return reject(err);

      return resolve(result);
    });
  })
}

async function fetchData(command) {
  await connect();
  const result = await query(command);
  con.close();
  return result;
}

For more information on Promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Additional resources on Async Functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

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

Is it possible to adjust the color and placement of the CircularProgress component?

Utilizing the CircularProgress component provided by Material has been a goal of mine. In my efforts to achieve this, I developed a component with the intention of customizing its color: import React, { Component } from 'react'; import { withSt ...

Caching HTML5 videos in Google Chrome

I am currently in the process of building a website and have successfully added an HTML5 video. However, I encountered an issue when attempting to change the video file in the background for users to upload a new one. Despite updating the video URL, Chro ...

Optimal project folder organization for a web application utilizing Grunt alongside npm, bundler, and composer

Currently, I have a project set up for a web application using Grunt to automate build tasks. SASS and Compass are used for styling, while Composer manages PHP dependencies. The folder structure looks like this: -project |-build |-node_modules |-src | ...

Struggling with converting blob file to an image within a NextJS application using data from a MySQL database

Currently, I am in the process of working on a project where I need to retrieve an image stored as a blob file in my database. However, for some reason, the image is not displaying properly. Here is the code snippet from the first file, products.jsx: impo ...

Seeking assistance in configuring Reddit OAuth using Node.js

I've been facing difficulties with this issue for a few days now and I couldn't find the necessary information in the Reddit API documentation to obtain oauth access using node. After registering my application with Reddit, I set 'http://loc ...

Leverage the Google Drive API for the storage of app-specific data

I'm currently developing a JavaScript application that runs on the client side and need to store a JSON object containing configuration details in a Google Drive Appdata file. Through the Google Drive API, I can successfully check for the file within ...

Optimal approach for handling user authorizations in a REST API with JWT implementation (Node.js + mongoose)

I am still getting the hang of working with mongoose and mongoDB, and I'm wondering what is the most effective method to prevent users from altering other users' information once they have logged in. Currently, my authentication system uses JWT, ...

Encountering issues with the command npm install --save web-animations-js, the

Issue encountered while trying to run "npm install --save web-animations-js". It seems like the request to https://registry.npmjs.org/web-animations-js failed due to a mismatch in the Hostname/IP in the certificate. The error message indicates that the Hos ...

Inconsistencies in grunt-ng-constant target operations

I encountered a strange issue with grunt-ng-constant where only 2 out of the 3 targets are working. Here is how my configuration is set up: grunt.initConfig({ ngconstant: { options: { space: ' ', wrap: '"use strict";&bso ...

Sorting by joined table

I'm having some trouble joining two tables and ordering the query results by a specific column in the table I'm joining. Everything seems to be working fine until I include ORDER BY cm.num, then I encounter the following error: Call to a member ...

Displaying search results seamlessly on the same page without any need for reloading

I am looking to create a search engine that displays results without the need to refresh the page. I have come across using hash as a potential solution, but I don't have much knowledge about web programming. So far, with the help of tutorials, I have ...

A guide on retrieving real-time data from PHP using Ajax

Being new to Ajax, I am struggling to grasp how to retrieve changing variable values from php. Below is the code snippet that I have been working on: <?php $pfstatetext = get_mypfstate(); $cpuusage= cpu_usage(); ?> <div id="show"> <c ...

deploying both my backend and frontend on firebase platform

My test project is created using React JS for the frontend and Node JS for the backend, organized in their respective folders: -frontend (folder) ---- React JS -backend (folder) ---- Express JS It works perfectly locally, but now I want to publish it ...

AngularJS checkbox validation requires a minimum of two checkboxes to be selected

When using AngularJS, I am looking to create a validation rule where a minimum of 2 checkboxes must be checked for the input to be considered valid. Here is what I have attempted: <div ng-repeat="item in items"> <label><input type="chec ...

transferring a function from a main component to a nested component using swipeout functionality in react-native

I am attempting to transfer a function from a parent container to a child container within react native. The user is presented with a list of items on the screen, where they can swipe the list to reveal additional options. Child import React from &ap ...

Unsubscribe from the Event Listener in Node.js

In light of this inquiry (linked here), can the Listener be eliminated from within the callback function? To illustrate: let callback = function(stream) { if(condition) performAction(); else server.removeListener('connection', cal ...

Execute a Cron Job every half an hour following the onCreate event in Firestore

Looking to set up a cron job or scheduler that runs every 30 minutes following an onCreate event in Firestore. The goal is to execute a cloud function that retrieves documents created within the last 30 minutes, validates them against a JSON schema, and ...

Unlocking bundles of worth through javascript coding

Is there a way to retrieve a set of values using javascript? Upon page load, I am looking to display an alert showing the value '0-1' for any checked checkboxes. View example here var checkBoxes = document.getElementsByName('mailId[]&apos ...

Is it possible to extract the body from the post request using req.body.item?

After working with Express, I learned how to extract body data from a post request. Most examples showed that using req.body.item should retrieve the desired value for tasks like inserting into a table. However, in my case, I found that I couldn't ac ...

Is there a way to consistently apply default props to a styled component?

Currently, I am working with React, Material UI, and Styled Components. My goal is to create a personalized Input field where the size='small' is always passed as a prop to my component. To clarify, if the user neglects to include the size attri ...