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

Error encountered when connecting to MongoDB: 'MongoServerSelectionError'

const uri = 'mongodb+srv:<username>//:<passwod>@chatapp-qrps3.azure.mongodb.net/test?retryWrites=true&w=majority' const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }) client.c ...

Dynamic content modal

Recently, I started exploring react native. In my application, there are 5 buttons on the screen. Each of them triggers the same <Modal>, but the content inside it changes based on the button clicked. For example, if I click the first button, a tex ...

Encountering issues with AJAX requests using jQuery

Hey there, I'm attempting to make an AJAX call in a C# page and I'm running into some issues. Below is my jQuery code: $(document).ready(function () { $.ajax({ type: "POST", url: "conteudo.aspx/GetNewPost", data: { i ...

Issue with Socket.IO: socket.on not executed

Recently, I devised a custom asynchronous emitter for implementing a server -> client -> server method. Regrettably, the functionality is not meeting my expectations. Although it emits the event, it fails to execute the callback as intended. Upon a ...

Steps for converting TypeScript code to JavaScript using jQuery, without the need for extra libraries or frameworks like NPM

My single-page dashboard is quite basic, as it just displays weather updates and subway alerts. I usually refresh it on my local machine, and the structure looked like this: project/ index.html jquery-3.3.1.min.js script.js I decided to switch it t ...

How to Retrieve Results Using Async in Node.js Module?

I am currently developing an internal NPM module for my company to enable applications to communicate with a hardware device using an existing library. The challenge I am facing is implementing a method that must execute asynchronously. This function shoul ...

What is the best way to refresh flexslider after it has been updated via AJAX?

At first, my slider is functional upon loading the page. However, after making an ajax call and receiving new slides to populate the slider, it becomes deactivated (as expected) https://i.sstatic.net/LC0yG.png Is there a method to reinitialize the flexsl ...

SQL where exist returns no results

My goal is to retrieve a list of operators in my database who are currently available for new assignments, meaning they have completed their previous jobs. However, despite my efforts to query the necessary tables and join the users table for additional de ...

Is there a common method for generating complex identifiers to be used as the HTML element's id, class, or name attributes

Is there a recommended method for "encoding" complex identifiers such as {Source:"ARCH.1", Code: "456-789.456 A+", SubNumber:##2} to be used in HTML elements' id, class, and name attributes? I could come up with something myself, but perhaps there is ...

Tips for displaying a modal to a user only once

I've developed a Flask application that enables multiple users to register and log in. To achieve this, I have incorporated sessions into my code. When new users land on the initial page, they are greeted with a modal introducing them to the platform. ...

What is the role of the .connect() method in Web Audio nodes?

Following the instructions found here, which is essentially a copy and paste from this I think I've managed to grasp most of it, except for all the node.connect()'s As far as I can tell, this code sequence is necessary to supply the audio anal ...

The function Jquery .stop does not exist

I am encountering an issue with the magicline.stop function while attempting to implement an underline sliding effect for my navbar. I have tried to troubleshoot the problem but have been unsuccessful so far. Below is the code snippet: <nav class=" ...

Converting an Array of Users to an Array of Email Addresses Using Google Apps Script

I am currently in the process of creating a script using Google Apps Script. My goal is to verify whether a user with the email address [email protected] has viewing or editing privileges for a folder. If the user does not have either privilege, I wa ...

The references to the differential loading script in index.html vary between running ng serve versus ng build

After the upgrade to Angular 8, I encountered a problem where ng build was generating an index.html file that supported differential loading. However, when using ng serve, it produced a different index.html with references to only some 'es5' scri ...

Conceal button divider on pager in Jqgrid

Within my grid setup, there are 3 buttons placed in the pager section: 'Refresh', 'Constution', and 'Developed'. These buttons are separated by two vertical navSeparators. Upon grid load, the 'Developed' button is hi ...

Should arrays of objects be kept in databases or JavaScript files?

Here is a small excerpt from an array of objects utilized on my website. It's just a snippet and not the full JS file. I have several JS files like this, some reaching up to 500 lines of code. Currently delving into databases ...

Utilizing Angular JS to Manage Controller Events

I am currently working on an application that requires saving a large amount of data in cascade, similar to a typical master-detail view. Within this view, there is a "Save All" Button which saves each row in an iteration. This process triggers jQuery cus ...

Having issues with @react-three/drei in next.js environment

Having trouble using drei materials and other features like MeshWobbleMaterial, MeshDistortMaterial, or ContactShadows? You may encounter errors such as: react-three-fiber.esm.js:1383 Uncaught TypeError: Cannot read property 'getState' of null a ...

What are the steps to modify the sign in page on keystone.js?

I recently started using keystone.js and I'm having trouble locating the sign in page within the files. I've searched through all of the keystone.js files but can't seem to find where it's written. Can someone please guide me on how to ...

Interactive map navigation feature using React.js

Can someone help me figure out how to create a dynamic map with directions/routes? I am currently using the Directions Renderer plugin, but it only shows a static example. I want to generate a route based on user input. Below is the code snippet: /* ...