【问题标题】:How can i get result from export module using async/await如何使用 async/await 从导出模块中获取结果
【发布时间】:2018-09-30 10:09:15
【问题描述】:

如何使用 async/await 或 promise 从导出模块获取 client.db(db_name) 到 main.js ...

ma​​in.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);
  });
};

【问题讨论】:

    标签: javascript node.js asynchronous async-await


    【解决方案1】:

    从您的 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);
      });
    };
    

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

    ma​​in.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}`);
    });
    

    【讨论】:

    • 也可以在创建用户集合后将app.listen() 调用放在then 中,以便服务器在访问数据库之前不接受请求。
    猜你喜欢
    • 2021-04-06
    • 2021-08-28
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2021-09-02
    • 2020-09-09
    • 1970-01-01
    相关资源
    最近更新 更多