我对模块创建还比较陌生,想了解一下module.exports和等待异步函数(例如mongo连接函数)完成并导出结果的相关知识。在模块中使用async/await变量可以得到正确定义,但是在尝试通过require模块记录它们时,它们会显示为未定义。如果有人能指点我正确的方向,那就太好了。以下是我目前的代码:
// module.js
const MongoClient = require('mongodb').MongoClient
const mongo_host = '127.0.0.1'
const mongo_db = 'test'
const mongo_port = '27017';
(async module => {
var client, db
var url = `mongodb://${mongo_host}:${mongo_port}/${mongo_db}`
try {
// Use connect method to connect to the Server
client = await MongoClient.connect(url, {
useNewUrlParser: true
})
db = client.db(mongo_db)
} catch (err) {
console.error(err)
} finally {
// Exporting mongo just to test things
console.log(client) // Just to test things I tried logging the client here and it works. It doesn't show 'undefined' like test.js does when trying to console.log it from there
module.exports = {
client,
db
}
}
})(module)
以下是需要引入该模块的JavaScript代码
// test.js
const {client} = require('./module')
console.log(client) // Logs 'undefined'
我对js比较熟悉,目前还在积极学习和探索像async/await等功能,但是...我真的弄不清楚那个问题