如何使用async/await从导出模块获取结果 [英] How can i get result from export module using async/await
本文介绍了如何使用async/await从导出模块获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用async/await或promise ...将client.db(db_name)从导出模块获取到main.js中...
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);
});
};
推荐答案
从您的config.js
文件中返回承诺. mongodb客户端直接支持诺言,只是不通过回调参数,并使用then
.
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);
});
};
然后调用,然后在promise处理程序中进行其余操作:
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}`);
});
这篇关于如何使用async/await从导出模块获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文