Unable to utilize the resolved value received from a promise and returned from it

Within the code snippet below, I am retrieving a Table object from mysql/xdevapi. The getSchema() and getTable() methods return objects instead of promises. The purpose of this function is to return a fulfilled Table object that can be used synchronously in other parts of the code.

// dbutils.js    
var mysqlx = require('@mysql/xdevapi');
var settings = require('./settings');

exports.getTable = (tableName) => {
  return mysqlx.getSession(settings.connectionProperties)
  .then(dbSession => {
    let table = dbSession.getSchema('shizbot').getTable(tableName);
    console.log("dbutils.getTable is returning table: " + table.getName())
    return table;
  })
  .catch(error => {
    console.log(error);
  })
}

However, when invoking the above method within this piece of code, I encounter a TypeError while attempting to execute a method on the returned Table object. The logged value of the Table object appears as {}. (Interestingly, there is other code where the Table object functions correctly inside the mentioned then() method.)

// db_user.js
var dbutils = require('./dbutils');

function getUserTable() {
  let table = dbutils.getTable('user');
  console.log("table: " + JSON.stringify(table));  //  table: {}  ???
  console.log("dbuser.getUserTable is returning table: " + 
  table.getName()) // TypeError: table.getName is not a function
return table;
}

Furthermore, the order of events in my logs seems unexpected. What could be causing this? While I understand that utilizing promises may be a better approach and refactor downstream code accordingly, why does the current code fail to function? I'm looking to gain a deeper insight into combining asynchronous and synchronous code.

Thank you!

Console Output:
running /authenticate route.
table: {}
Error while authenticating: TypeError: table.getName is not a function
POST /admin/authenticate 500 24.089 ms - 40
dbutils.getTable is returning table: user

Answer №1

There seems to be a timing issue as your console.log commands are running prior to the completion of the asynchronous operation table.getTable('user').

Answer №2

The console.log() statements in your code are being executed before the async function is ready to fetch data. This can be resolved by adding .then() statements for the Promise function, ensuring that the data is successfully fetched and displayed in the table as shown below:

// database_user.js
var dbUtils = require('./dbUtils');

function retrieveUserTable() {
    dbUtils.getTable('user')
        .then(function(result) {
            console.log("Retrieved table: " + JSON.stringify(result));
            console.log("The getUserTable function returned: " + result.getName());
            return result;
        });
}

Feel free to test out this revised code and let me know if you encounter any issues.

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

The digest string for the crypto.pbkdf2Sync function is malfunctioning

I've been working on revamping the authentication system for an old application that previously ran on node 4.5, but I keep encountering an error whenever I attempt to log in. TypeError [ERR_INVALID_ARG_TYPE]: The "digest" argument must be one of type ...

Implementing pagination in a table with the help of jQuery

I've been working on this code for the past few days and I'm struggling to find a solution that meets my requirements. What I need is pagination within a specific section of a table, with the following actions/events: When clicking previous o ...

Mongoose retrieves the entire document, rather than just a portion of it

I'm currently experiencing an issue with my mongoose query callback from MongoDB. Instead of returning just a specific portion of the document, the code I'm using is returning the entire document. I have verified that in the database, the 'p ...

Ways to verify that a javascript function generates an object and executes a method within that object

Currently, I am in the process of updating server code written in nodejs and incorporating unit tests into the mix. However, I have encountered a challenge that I need assistance with: classX.prototype.methodX = function () { // Create new session ...

Modifying multiple heading tags simultaneously with jQuery

Currently utilizing jQuery to append a string to all heading tags (h1, h2,..., h6) and display it on the screen. Seeking guidance specifically for the replacing aspect, and open to solutions using plain javascript as well. The code I have so far, which I ...

Issue with Ajax not sending query string to ASP.NET controller

I am currently working with an Ajax function that serializes data sent from my view into a query string. Here is the code snippet: UpdateFIConfig: function ($appForm) { var valid = $appForm.valid(); //if not valid the validate plugin will take ca ...

Using ExpressJS and Jade to submit a form using the POST method and redirecting to a specified path

I am exploring node, express and jade for the first time and working on a small application that requires users to enter their name and password in a form. The app then redirects them to a path based on their username. Here is the code snippet to achieve ...

Altering the language code on LinkedIn

As a beginner in programming, I successfully added the linkedin share button to my test webpage. Now, I am hoping to make the button change language based on the user's language selection on the webpage. Linkedin uses a five character language code ( ...

Unlocking the Power of Typescript and ReactJS: Maximizing Efficiency with Previous State

I'm encountering difficulties implementing the previous state in React 18 with Typescript version 4.8.3. Here is my refreshToken code and I'm receiving the following error: Value of type '(prev: any) => any' has no properties in c ...

Can someone explain to me the meaning of "var vm = $scope.vm = {}" in AngularJS?

While reading through the angularJS api, I came across some code that looked like this: myApp.controller('MyController', ['$scope', function($scope) { var vm = $scope.vm = {name:'savo'}; } ]); Initially, this mul ...

The number of subscribers grows every time $rootscope.$on is used

I currently have an Angular controller that is quite simple: angular.controller('appCtrl', function ($scope, $rootScope) { $rootscope.$on('channel.message', function () { // do something here } }); In addition, I have a ...

Barba.js (Pjax.js) and the power of replacing the <head> tag

I have been using barba.js to smoothly transition between pages without having to reload the entire site. If you want to see an example, take a look here. Here is a snippet of code from the example: document.addEventListener("DOMContentLoaded", func ...

Issue with TinyMCE Editor: Inoperative

<script type="text/javascript" src="<your installation path>/tinymce/tinymce.min.js"></script> <script type="text/javascript"> tinymce.init({ selector: "textarea", theme: "modern", plugins: [ "advlist autolink li ...

What is the best way to create subpages within a survey?

If I want to create a survey page on the web with multiple questions, but I am facing a challenge. I do not want to have several different pages and use a "Next Button" that links to another page. I am struggling to come up with ideas on how to implement ...

The useStarRating() hook continues to display 0 even after the user has interacted with the star component

I've created a custom useStarRating hook to manage the state of a star rating component in my React project. Everything seems to be working properly, but I'm facing an issue with retrieving the updated value of currentValue after the user interac ...

When I engage with the input field, it ceases to be in focus

Here is the code I've been working on: https://github.com/Michael-Liendo/url-shortener/blob/main/src/pages/index.js If you want to see the issue for yourself, check it out at: ...

Every time I try to restart my React Project, it seems to encounter strange issues that

Currently, I am following a fullstack React tutorial which you can find here: React Tutorial I have encountered an issue where every time I close my laptop and reopen the project, npm start throws a strange error. Initially, I tried to fix it by starting ...

Steps to bring life to your JavaScript counter animation

I need to slow down the counting of values in JavaScript from 0 to 100, so that it takes 3 seconds instead of happening instantly. Can anyone help me with this? <span><span id="counter"> </span> of 100 files</span> <s ...

Using jQuery to iterate through rendered HTML with the ForEach function

I am utilizing JS/jQuery code to extract the cell value of an ASP DetailsView control (rendered HTML), validate it against a condition, and hide a specific div based on the result. Specifically, the code is examining whether the cell value is formatted lik ...

What are some techniques for reducing the number of pages in my Carousel?

I need help figuring out how to set a limit of noOfPages for the number of pages per carousel. The functions in my code below don't implement this and I'm unsure how to do it. const itemsPerPage = 6; const [page, setPage] = React.useState(1); ...