Node.js异步/等待模块导出



我对模块创建有点陌生,想知道module.exports并等待异步函数(例如mongo连接函数(完成并导出结果。变量在模块中使用 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 相当熟悉,并且仍在积极学习和研究异步/等待和类似功能之类的东西,但是是的......我真的想不通那个

您必须同步导出,因此无法导出client并直接db。但是,您可以导出解析为client的承诺并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)不是一个合适的错误处理程序,如果你不能处理错误只是崩溃

上面由 @Jonas Wilms 提供的解决方案正在工作,但每次我们想要重用连接时都需要在异步函数中调用 requires。 另一种方法是使用回调函数返回 mongoDB 客户端对象。

蒙戈.js:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<user>:<pwd>@<host and port>?retryWrites=true";
const mongoClient = async function(cb) {
const client = await MongoClient.connect(uri, {
useNewUrlParser: true
});
cb(client);
};
module.exports = {mongoClient}

然后我们可以在不同的文件(Express route或任何其他js文件(中使用mongoClient方法。

应用.js:

var client;
const mongo = require('path to mongo.js');
mongo.mongoClient((connection) => {
client = connection;
});
//declare express app and listen....
//simple post reuest to store a student..
app.post('/', async (req, res, next) => {
const newStudent = {
name: req.body.name,
description: req.body.description,
studentId: req.body.studetId,
image: req.body.image
};
try
{
await client.db('university').collection('students').insertOne({newStudent});
}
catch(err)
{
console.log(err);
return res.status(500).json({ error: err});
}
return res.status(201).json({ message: 'Student added'});
};

最新更新