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