简体   繁体   中英

Can I export the result of an asynchronous function with module.export?

For example, in this code provided by npm mongodb to establish a connection:

const MongoClient = require('mongodb').MongoClient;
MongoClient.connect(url).then(connection => {
  const db = connection.db('myDB');
});

I wish to export db to use in other files. The first file that requires it will need to wait for the promise to resolve, the subsequent files won't need to. Is there a way to achieve this?

Of course, there are multiple other ways to write the code in this particular case regarding mongodb, but I'm asking this question in a more generic sense.

Thanks!

Can I export the result of an asynchronous function with module.export?

No, you cannot directly export something that is obtained via an asynchronous function call.

module.exports is assigned and returned synchronously (and you can't change that). So, if you are assigning to module.exports asynchronously, the module will load and return before your asynchronous function returns. The caller will have to have some means of waiting until the asynchronous operation is done to get its result. The usual ways to do that are via a callback function or by exporting a promise that resolves with the desired value.

The usual work-around for this is to export a promise (I call it dbPromise here) and the caller can then use something like:

 const myModule = require('someModule');
 myModule.dbPromise.then(db => {
     // can use db in here
 });

Other related references:

Importing / exporting only after certain promises have resolved

exporting after promise finishes

value from promise is not being exported to another module

Here i have made a very simple script for you i hope this will help

  var mongodb = require('mongodb').MongoClient;
  var settings = require("./settings.js");
  var ObjectId = require('mongodb').ObjectID;
  var db = {
    removeData: function(collection, query, callback) {
      mongodb.connect(settings.db_url, function(err, client) {
        var database = client.db(settings.db_name);
        if (err) throw err;
        database.collection(collection).remove(query, function(err, result) {
          client.close();
          if (err) throw err;
          callback(result);
        });
      });
    },
    selectData: function(collection, query, callback, project = false) {
      mongodb.connect(settings.db_url, function(err, client) {
        var database = client.db(settings.db_name);
        if (err) throw err;
        if (project !== false) {
          console.log("Project is not false");
          console.log( project);
          database.collection(collection).find(query, project).toArray(function(err, result) {
            client.close();
            if (err) throw err;
            callback(result);
          });
        } else {
          database.collection(collection).find(query).toArray(function(err, result) {
            client.close();
            if (err) throw err;
            callback(result);
          });
        }
      });
    },
    insertManyData: function(collection, obj, callback) {
      mongodb.connect(settings.db_url, function(err, client) {
        var database = client.db(settings.db_name);
        database.collection(collection).insertMany(obj, function(err, res) {
          if (err) throw err;
          client.close();
          callback(res);
        });
      });
    },
    insertData: function(collection, obj, callback) {
      obj._id = ObjectId();
      mongodb.connect(settings.db_url, function(err, client) {
        var database = client.db(settings.db_name);
        var id = db.ObjectId();
        obj._id = id;
        obj.__id = id.toString();
        database.collection(collection).insertOne(obj, function(err, res) {
          if (err) throw err;
          client.close();
          callback(res);
        });
      });
    },
    updateData: function(collec, query, values, callback) {
      mongodb.connect(settings.db_url, function(err, client) {
        var database = client.db(settings.db_name);
        database.collection(collec).updateOne(query, values, function(err, res) {
          if (err) throw err;
          client.close();
          callback(res);
        });
      });
    },
    aggregate: function(collec, query, callback) {
      mongodb.connect(settings.db_url, function(err, client) {
        var db = client.db(settings.db_name);
        var collection = db.collection(collec);
        collection.aggregate(query).toArray(function(err, docs) {
          client.close();
          callback(docs);
        });
      });
    },
    ObjectId: function(id) {
      return ObjectId(id);
    }
  }


  module.exports = db;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM