在下面的代码中,我获取了一个表对象(来自 mysql/xdevapi)。 getSchema() 和 getTable() 方法返回对象,而不是 promise 。我的目的是让此函数返回一个 Table 对象(已实现的值),我可以在其他代码中同步使用它。
// 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);
})
}
但是,当我从这段代码调用上述方法时,我得到 TypeError trying to execute a method on the returned Table object,并且 Table 对象的值记录为 {}。 (顺便说一句,当在上面的 then() 方法中使用时,我还有其他代码可以很好地使用 Table 对象。)
// 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;
}
此外,我的日志显示了意外的事件顺序。到底是怎么回事?我意识到我可以(而且可能应该)利用 promise 并在下游重写我的代码,但为什么这段代码不起作用?我试图更好地理解如何混合使用异步和同步代码。
谢谢!
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
最佳答案
我相信这是因为您的 console.log
语句在您的异步 table.getTable('user')
完成之前执行。
关于javascript - 不能使用从 promise 解析和返回的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48713434/