Node.js Async/Await module export

前端 未结 2 1772
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 17:11

I\'m kinda new to module creation and was wondering about module.exports and waiting for async functions (like a mongo connect function for example) to complete and exportin

相关标签:
2条回答
  • 2020-12-10 17:17

    the solution provided above by @Jonas Wilms is working but requires to call requires in an async function each time we want to reuse the connection. an alternative way is to use a callback function to return the mongoDB client object.

    mongo.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}
    

    then we can use mongoClient method in a diffrent file(express route or any other js file).

    app.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'});
    };
    
    0 讨论(0)
  • 2020-12-10 17:33

    You have to export synchronously, so its impossible to export client and db directly. However you could export a Promise that resolves to client and db:

    module.exports = (async function() {
     const client = await MongoClient.connect(url, {
       useNewUrlParser: true
     });
    
      const db = client.db(mongo_db);
      return { client, db };
    })();
    

    So then you can import it as:

    const {client, db} = await require("yourmodule");
    

    (that has to be in an async function itself)

    PS: console.error(err) is not a proper error handler, if you cant handle the error just crash

    0 讨论(0)
提交回复
热议问题