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.
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
Your implementation is a bit strange. I think the following is more suitable.
a.js
b.js:
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.
Why is module.exports placed in the then callback function?
You must know that the main logic of a.js is executed asynchronously~~~
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