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

Javascript Node.js异步/等待模块导出,javascript,node.js,module,async-await,Javascript,Node.js,Module,Async Await,我对模块创建有点陌生,我想知道module.exports并等待异步函数(例如mongo connect函数)完成并导出结果。在模块中使用async/await正确定义变量,但是当试图通过要求模块来记录它们时,它们显示为未定义。如果有人能给我指出正确的方向,那就太好了。以下是我目前掌握的代码: // module.js const MongoClient = require('mongodb').MongoClient const mongo_host = '127.0.0.1' const

我对模块创建有点陌生,我想知道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等特性,但是是的。。。我真的无法计算出您必须同步导出的那一个,因此不可能直接导出
客户端
数据库
。但是,您可以导出解析为
客户端
数据库
的承诺:

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客户机对象

mongo.js:


我使用了mongodb官方节点驱动程序中的一些示例代码来进行测试。但总的来说,这对我来说是有用的。示例代码可以找到啊,我明白了。。最后,我将导出需要mongo连接的东西,而不是导出连接本身。不过,这是有道理的,谢谢:)@brocococonot很高兴提供帮助:)因为您返回了一个函数,这种方法将为每个需求打开一个新的连接。是吗?谢谢。所以我需要在我想要查询数据库的每一个函数中使用这个?感觉非常‘样板’@DevAKS
const abc=wait import(“/示例模块”)这将创建多个客户端…不确定是否需要。此外,如果在加载db客户端之前调用API端点,则API端点将响应错误。
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}
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'});
};