如何使用async / await从导出模块获取结果

时间:2018-04-19 19:37:39

标签: javascript node.js asynchronous async-await

如何使用async / await或promise ...将export.db(db_name)从export模块导入main.js ...

main.js

var express = require('express')
var app = express();

enter code here
// Web server port number.
const port = 4343;

require('./config/app_config')(app);
db = require('./config/data_config')(app);
db.collection('users');


app.listen(port, () => {
    console.log(`Server start at port number: ${port}`);
});

config.js

  module.exports = (app) => {
  const mongo_client = require('mongodb').MongoClient;
  const assert = require('assert');

  const url = 'mongodb://localhost:27017';
  const db_name = 'portfolio';

  mongo_client.connect(url, (err, client) => {
    assert.equal(null, err);
    console.log('Connection Successfully to Mongo');
    return client.db(db_name);
  });
};

1 个答案:

答案 0 :(得分:0)

config.js文件中返回承诺。 mongodb client supports promises directly,只是不传递回调参数并使用then

<强> config.js

module.exports = (app) => {
  const mongo_client = require('mongodb').MongoClient;
  const assert = require('assert');

  const url = 'mongodb://localhost:27017';
  const db_name = 'portfolio';

  return mongo_client.connect(url).then(client => {
    assert.equal(null, err);
    console.log('Connection Successfully to Mongo');
    return client.db(db_name);
  });
};

然后调用然后在promise处理程序中完成剩下的工作:

<强> main.js

var express = require('express')
var app = express();

// Web server port number.
const port = 4343;

require('./config/app_config')(app).then(db => {
  db.collection('users');
});

// as Bergi suggested in comments, you could also move this part to `then` 
// handler to it will not start before db connection is estabilished
app.listen(port, () => {
  console.log(`Server start at port number: ${port}`);
});