我对模块创建有点陌生,想知道module.exports并等待异步功能(例如mongo connect函数)完成并导出结果。可以在模块中使用async / await正确定义变量,但是当通过要求模块尝试记录变量时,它们显示为未定义。如果有人能指出我正确的方向,那就太好了。这是到目前为止我得到的代码:
// 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 …Run Code Online (Sandbox Code Playgroud)