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

筅森魡賤 提交于 2021-02-08 09:26:06

问题


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!


回答1:


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




回答2:


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;


来源:https://stackoverflow.com/questions/49991740/can-i-export-the-result-of-an-asynchronous-function-with-module-export

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!