javascript - external function call, promise, async and Mongo - confused
问题描述
Beginning to feel really thick here. Read a lot and I believe I understand promises and async-await decently well. However, I seem to struggle to use the function elsewhere, such that I can obtain the result (e.g. i get pending in another js file with: let dbConnection = dbOperations.openDatabaseConnection();).
Could someone explain to me why do I keep getting pending from the below functions (same function written with promise and asyncawait)? I can console.log the dbConnection result as expected prior to my return within the function. Also, I am particularly keen to understand promises in this sense, as it seems that many npm packages seem to return promises (and with my experience at least the async-await does not sit well with that? -> using async does not wait for resolve in my experience).
// Establish database connection
function openDatabaseConnection() {
let dbConnection = {};
return mongodb.connect(dbUri).then(conn => {
dbConnection.connection = conn;
return dbConnection;
})
.then(() => {
dbConnection.session = dbConnection.connection.db(dbName);
//console.log(dbConnection);
return dbConnection;
})
.catch(err => {
throw err;
});
};
// Establish database connection
async function openDatabaseConnection() {
let dbConnection = {};
try {
dbConnection.connection = await mongodb.connect(dbUri);
dbConnection.session = await dbConnection.connection.db(dbName);
} finally {
//console.log(dbConnection);
return dbConnection;
};
};
解决方案
这两个函数都再次返回一个承诺。
因此,在您的声明中let dbConnection = dbOperations.openDatabaseConnection();
,您指定了一个承诺。
因此,您需要执行以下操作:
dbOperations.openDatabaseConnection().then((dbConn) => ..)
或者
let dbConnection = await dbOperations.openDatabaseConnection();
(注意这需要包装在一个async
函数中)
推荐阅读
- javascript - 取消屏蔽日期时间 - 输入掩码
- javascript - 对网页进行实时更新时跟踪更改的方法
- ms-access - 根据 InfoPath 中的下拉菜单显示有关项目的信息
- php - 需要使照片以随机顺序出现但保持并排响应。
- r - 如何解决错误:找不到包根目录?
- ion-auth - codeigniter 中的 JWT 令牌(ion-auth)
- jquery - 单击某个图像后,如何更改另一个元素中的 img src 值
- rest - 关于 REST API 辩论的任何建议?
- python - 从 Django QuerySet 中获取所有值以及来自相关模型的其他字段
- scala - Python使用像scala这样的地图