我对模块创建有点陌生,想知道 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
and db
直接地。但是,您可以导出一个解析为的 Promiseclient
and 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)
不是一个合适的错误处理程序,如果你无法处理错误,就会崩溃
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)