我对模块创建有点陌生,想知道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 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)
这是需要模块的js
// test.js
const {client} = require('./module')
console.log(client) // Logs 'undefined'
我对js非常熟悉,并且仍在积极学习和研究诸如async / await之类的功能,但是,是的。。。
你必须同步输出,所以它不可能出口client
和db
直接。但是,您可以导出解析为client
和的Promise db
:
module.exports = (async function() {
const client = await MongoClient.connect(url, {
useNewUrlParser: true
});
const db = client.db(mongo_db);
return { client, db };
})();
因此,您可以将其导入为:
const {client, db} = await require("yourmodule");
(本身必须在异步函数中)
PS:console.error(err)
不是正确的错误处理程序,如果您不能处理错误,只会崩溃
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句