search

Home  >  Q&A  >  body text

node.js - nodejs中module.export为一个异步返回结果时该怎么做?

阿神阿神2914 days ago600

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 12:05:14

    Your implementation is a bit strange. I think the following is more suitable.

    a.js

    var MongoClient = require('mongodb').MongoClient;
    
    
    var main = {
      getResult: function(callback) {
        MongoClient.connect('mongodb://localhost:27017/local', function(err, db) {
    
          // Use the admin database for the operation
          var adminDb = db.admin();
          // List all the available databases
          adminDb.listDatabases().then(function(dbs) {
            var result = [];
            dbs.databases.forEach(function(element, index) {
              result.push(element.name);
            })
            db.close();
            callback(result);
          });
        });
      }
    };
    
    module.exports = main;

    b.js:

    var a = require("./a");
    
    a.getResult(function(result){
      console.log(result);
    });
    

    In addition, require js files do not need to have a .js extension. If you want to write asynchronously using promises instead of callbacks, please refer to bluebird.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 12:05:14

    Why is module.exports placed in the then callback function?
    You must know that the main logic of a.js is executed asynchronously~~~

    var data = require("a.js");
    console.log(data); 
    

    Recommendations:
    1) Export function module
    2) The export module inherits EventEmitter
    3) After the promise function is executed, send event notification
    4) Listen where the module is imported Notification of this event

    reply
    0
  • Cancelreply