node.js - nodejs中module.export为一个异步返回结果时该怎么做?
阿神
阿神 2017-04-17 12:03:14
0
2
601
阿神
阿神

闭关修行中......

reply all(2)
巴扎黑

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.

Peter_Zhu

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template