Understanding the method of recovering a nested promise

I am facing an issue with returning the result parameter from the getColumn function. Despite my attempts, it keeps logging as undefined.

The connection function establishes a connection to a SQL database and retrieves a data set through a query.

Is there a way for me to effectively pass the variable up the promise chain?

getColumn = function(columnName, table) {
  sql.connect(config.properties)
    .then(result => {
      let request = new sql.Request();
      request.query("SELECT " + columnName + " FROM " + table)
      .then(result => {
          // trying to return this 'result' from the getColumn function
          return result
      }).catch(err => {
          // Error handling for queries
      })
    }).catch(err => {
      // Error handling for connections
    })
} // 

console.log(getColumn('username', 'Login'))

Answer №1

Initially, attempting to directly return a value from getColumn() is not feasible. The function's internal operations are asynchronous, meaning the final value cannot be determined until after getColumn() has completed its execution. As a result, getColumn() currently returns undefined due to lacking a direct return value. The existing return statement pertains to an asynchronous .then() handler rather than the core getColumn() method. Given the asynchronous nature of getColumn(), it is impossible to simply return the end result. Instead, employing a promise or callback system is necessary. Considering that promises are already utilized within the function, opting for a promise-based approach would be most suitable.

To address this issue, you can modify getColumn() to return a promise and subsequently handle it using either .then() or await.

In order to return a promise, it is essential to propagate the underlying promises:

const getColumn = function(columnName, table) {
  // return promise
  return sql.connect(config.properties).then(result => {
    let request = new sql.Request();
    // chain this promise onto prior promise
    return request.query("SELECT " + columnName + " FROM " + table);
  });
} // 

getColumn('username', 'Login').then(val => {
   console.log(val);
}).catch(err => {
   console.log(err);
});

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

Integrating webpack with kafka-node for seamless communication between front

I am in the process of embedding a JavaScript code that I wrote into an HTML file. The script requires kafka-node to function properly, similar to the example provided on this link. To achieve this, I am using webpack to bundle everything together. I am fo ...

Can you please guide me on how to convert pug (jade) to html using npm scripts?

Struggling to construct my package.json file, I find myself facing a challenge when it comes to writing scripts. "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build-css":"node-sass --output-style compressed -o bu ...

Is the variable empty outside of the subscribe block after it's been assigned?

Why is a variable assigned inside subscribe empty outside subscribe? I understand that subscribe is asynchronous, but I'm not sure how to use await to render this variable. Can someone please help me and provide an explanation? I am attempting to retr ...

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 ...

Enhancing presentation with a multitude of pictures

I am currently in the process of developing a slideshow feature that includes an extensive collection of images for users to navigate through using 'next' and 'previous' buttons. At the moment, each time a user clicks on the navigation ...

Is it possible to use both interfaces and string union types in TypeScript?

My goal is to create a method that accepts a key argument which can be either a string or an instance of the indexable type interface IValidationContextIndex. Here is the implementation: /** * Retrieves all values in the ValidationContext container. ...

Using JavaScript to launch a new window with an array of parameters

I am working on an asp.net mvc 3 application that has an Action Method for handling GET requests and returning a page. The code snippet is shown below: [HttpGet] public ActionResult Print(IEnumerable<string> arrayOfIds) { ....................... ...

Determine the present height of the current class and substitute it with another class that has the same

My wordpress blog theme has an ajax pagination feature that works well, except for the fact that when a user clicks on the next page link, the entire posts area disappears while the new content is loading. I would like to maintain the same container dimens ...

Unexpected value detected in D3 for translate function, refusing to accept variable

I'm experiencing a peculiar issue with D3 where it refuses to accept my JSON data when referenced by a variable, but oddly enough, if I print the data to the console and manually paste it back into the same variable, it works perfectly fine. The foll ...

Utilizing the power of JavaScript within CSS styling

I may be new at this, so excuse the silly question, but I'm currently working on developing an app with phonegap. In order to ensure that my app looks consistent across all devices, I need to define the height of each device. I know that JavaScript ca ...

Clicking on a DIV using jQuery, with anchor elements

I have a method for creating clickable divs that works well for me: <div class="clickable" url="http://google.com"> blah blah </div> Afterwards, I use the following jQuery code: $("div.clickable").click( function() { window.location ...

What is the best way to ensure a table is responsive while maintaining a fixed header? This would involve the table scrolling when it reaches the maximum viewpoint, while also keeping

Can anyone help me create a responsive table with a fixed header that scrolls when it reaches the maximum viewpoint without scrolling the entire page? I've tried using box-sizing: border-box; and overflow-x:scroll; but it didn't work. Any suggest ...

Encountering issue while starting npm: expressjs server facing problem with MongoDB

Running npm start on Windows went smoothly, but I encountered an error when trying it on macOS. The error message is as follows: > node ./bin/www.js www error: SyntaxError: Unexpected token ? If you require any additional information, please do not he ...

Why is it difficult to display data fetched through getJSON?

The test-json.php script retrieves data from the database and converts it into JSON format. <?php $conn = new mysqli("localhost", "root", "xxxx", "guestbook"); $result=$conn->query("select * From lyb limit 2"); echo '['; $i=0; while($row ...

The URL is being modified, yet the page remains static in the React application

I've been working on setting up a router with react-router-dom, but I'm facing an issue where my URL gets updated without the page routing to the specified component. Here's a snippet from my App.js: import "./App.css"; import { Br ...

Why is it that consolidating all my jQuery plugins into one file is ineffective?

Prior to this, I included the following scripts: <script type="text/javascript" src="{{MEDIA_URL}}js/plugins/json2.js"></script> <script type="text/javascript" src="{{MEDIA_URL}}js/plugins/jquery-msdropdown/js/jquery.dd.js"></script&g ...

AngularJS can be used to display a webpage

After facing the need to print a given page using AngularJS, I came up with a simple solution as shown below: <div class="modal fade" id="extrait" aria-hidden="true" data-backdrop="false"> <table class="table table-hover table-bordered" i ...

What is the method for toggling background URLs?

Currently, I am utilizing flaunt.js by Todd Moto for my navigation system. My goal is to seamlessly switch the hamburger image with another image when the mobile-menu is shown and hidden. Check out the demo here. For a detailed tutorial, visit this link. ...

Issue: Incorrect parameters for executing the MySQL statement

Currently, I am working on a nodeJs project and utilizing the npm package mysql2 for connecting to a MySQL database. This is how my MySql Configuration looks like:- let mysql = MYSQL.createConnection({ host: `${config.mysql.host}`, user: `${config.mys ...

Transform the characters within a string into corresponding numerical values, calculate the total sum, and finally display both the sum and the original string

I'm looking to convert a string containing a name into numerical values for each character, ultimately finding the sum of all characters' numerical values. Currently, only the first character's value is being summed using .charAt(). To achie ...