Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

javascript - How can i get result from export module using async/await

How can i get client.db(db_name) from export module to main.js using async/await or promise ...

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);
  });
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Return a promise from your config.js file. mongodb client supports promises directly, just do not pass the callback parameter and use 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);
  });
};

And call then and do the rest in the promise handler:

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}`);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...