Guarantee of SQL integration within JavaScript

I am trying to retrieve the value of the message variable, but all I see in the console is the following: result [object Promise]

async function Testing() {
  let response = await new Promise((resolve, reject) => {
    db.query("SELECT * FROM `nitrоboost`", (error, rows) => {
      if (error) {
        console.log(error);
      }
    });
  });
  return response;
}
let data = Testing();
console.log(`result` + data);

Answer №1

When working with the Testing function, it is important to remember that it operates asynchronously, resulting in the return of a Promise.

To access the value of a Promise, you must utilize either the await syntax or the .then() method.

Additionally, in order to obtain the output, the query result needs to be passed to the res callback:

// For demonstration purposes, we create a mock db object...
const db = { 
    query(sql, cb) {
        console.log('Executing query:', sql);
        setTimeout(() => cb(null, [{ id: 1, data: 'some data' }]), 500)
    }
}


async function Testing() {
  return new Promise((res, rejects) => {
    db.query("SELECT * FROM `nitrоboost`", (error, row) => {
      if (error) {
        console.log(error);
        // Error passed to the rejects callback
        rejects(error);
      } else {
        // Result passed to the res callback
        res(row)
      }
    });
  });
}

async function runTesting() {
    let message = await Testing();
    console.log(`result:`,  message);
}

runTesting();
    
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Display the Express response in an HTML element by utilizing the fetch API

I am currently developing a small node/express project that showcases the bcyrpt hashed value of user input. While I have been successful in displaying the hashed value in the server's console.log, I am facing difficulties in injecting this value into ...

What is the best way to pass a parameter with a slash in a GET request using jQuery's .ajax() function?

I'm currently faced with the task of generating a specific URL to make an API call using jQuery's .ajax() function: https://www.airnowapi.org/aq/forecast/zipCode/?format=application/json&zipCode=02144&date=2016-11-26&distance=25& ...

What are the steps to set up auto-building with create-react-app?

I've been utilizing create-react-app for some time now. Autoreloading with 'npm start' or 'yarn start' has been working well on its own, but now I'm facing another issue. Currently, I am running the app on an Express server th ...

Using ng-disabled on input elements within an ng-repeat directive

Showing different inputs based on an array looks like this <div data-ng-repeat="n in langInput.values"> <input type="text" id="auction_name_{{n.selected}}" class="form-control" name="auction_name_{{$index}}" ...

Is there a way for me to display information from a secondary child component by simply clicking a button on the main component instance?

Consider a scenario where there is a main instance, a child component named "movie-card," and another child component within "movie-card" called "link-btn." The objective is to create a selector that loops through the "link-btn" component using v-for. Addi ...

Learn how to implement pagination in AngularJS using the $http service

I need assistance in implementing pagination using Angularjs within the Ionic Framework. Can someone provide guidance on how to code pagination for fetching data from a JSON URL? controller.js angular.module('starter.controllers', []) .control ...

Combining model with a string in an expression in AngularJS version 1

Can this text be transformed into an expression using ecmaScript 2015? The || operator seems to be causing issues. {{ ::$ctrl.realEstateProjectCurrentProduct.housingTax + ' €' || $ctrl.noDataMessage }} ...

Transform your standard HTML buttons into a collective of radio buttons

Looking for a way to make some ordinary buttons function as radio buttons without adding another library to the project. Any suggestions on how this can be achieved using just HTML and JavaScript/jQuery? Appreciate any help, thank you. ...

Updating Rails Partial with JSON Data

Updating a partial by appending fetched Facebook posts using the koala gem requires some code adjustments. Here is an example of how to achieve this: # feed_controller.rb def index end def fb_feed @fb_feed = .. respond_to do |format| format.js { ...

Extracting data from the response object and injecting it into the request

Once the file has been successfully uploaded, the 'uploadSuccess' callback event is triggered, providing information about the newly created media. The 'hashed_id' value within this object is crucial for my PUT request. I attempted to ...

Automatically relaunch NodeJS application upon app failure

I am looking for a way to automatically restart my NodeJS (Express) app after crashes with errors. I am familiar with the forever npm package, but all the examples I found were for running the app in development. My goal is to implement this in production ...

Implementing Ajax functionality in MVC 3 to return a partial view

I wanted to express my gratitude for this invaluable site that has taught me so much. Currently, I am working on an MVC3 component where I need to populate a selectlist and upon user selection, load a partial view with the relevant data displayed. Everythi ...

Upcoming API and backend developments

When working with the NEXT project, API Routes provide the ability to create an API endpoint within a Next.js application. This can be achieved by creating a function in the pages/api directory following this format: // req = HTTP incoming message, res = H ...

AngularJS routing with html5mode causing 404 error when using htaccess

I am currently working on my very first angularjs application using version 1.6x, and I am encountering some 404 errors with my router. Here is how my router is set up: app.config(function($routeProvider, $locationProvider) { $locationProvider.html5M ...

What is the correct way to utilize JavaScript's clearTimeout function with arguments?

I came up with a simple function to mimic the movement of window blinds. It runs on a server that receives requests with a direction parameter determining whether the blind should move UP, DOWN, or STOP. The simulation works like this: upon receiving a re ...

I'm having trouble removing records from MySql

I am facing an issue with two tables in my database. Table a is referencing table b, or so I believe. Whenever I attempt to delete the entire package using the following query: $query="DELETE a, b FROM classified as a, $sql_table as b WHERE a.ad_id = &ap ...

An interactive SQL query

Imagine having a real estate website where users can search for properties based on their preferences. I want to create a feature on the default page that displays the number of posts matching the user's parameters. To illustrate, here is an example ...

Struggling to interpret the array of objects retrieved from a call to UrlFetchApp.fetch in Google App Script

When UrlFetchApp.fetch is called, it provides an array of objects that are stored in the variable 'results': var results = [{"Category 1": "Benefits/Compensatio", "Category 2": "Compensation", "Category 3": "Recognizing You", "Processing Team": ...

Associate the right-click action with Angular Material

I'm currently working with Angular Material. My goal is to develop a directive that allows me to trigger a right-click event on an element. This is what I have attempted so far: JavaScript: app.directive('rightClick', ["$parse", function ...

How can I deactivate the today button in the angular-ui bootstrap datepicker popup?

Currently, I am working with two dates: StartDate and EndDate which are being managed using the angular-ui-bootstrap datepicker. When a user selects a StartDate (which must be greater than today's date), I want to ensure that the min-date of the EndD ...