如何导出仅在异步回调中可用的对象? [英] How to export an object that only becomes available in an async callback?
问题描述
我有一个db.js文件,我在其中设置了一个MongoDB连接。我想将数据库对象导出到我的主app.js文件中:
I have a db.js file in which I set up a MongoDB connection. I would like to export the database object into my main app.js file:
// db.js
require('mongodb').MongoClient.connect(/* the URL */, function (err, db) {
module.exports = db;
});
// app.js
var db = require('./db');
app.get('/', function (req, res) {
db.collection(/* … */); // throws error
});
错误是:
TypeError:对象#没有方法'集合'
TypeError: Object # has no method 'collection'
那么,如何导出 db
对象是否正确?
So, how can I export the db
object properly?
推荐答案
最佳选项,如中的建议< a href =https://stackoverflow.com/users/670396/elclanrs> elclanrs ,是出口承诺:
The best option, as suggested in the comments by elclanrs, is to export a promise:
// database.js
var MongoClient = require('mongodb').MongoClient,
Q = require('q'),
connect = Q.nbind(MongoClient.connect, MongoClient);
var promise = connect(/* url */);
module.exports = {
connect: function () {
return promise;
}
}
// app.js
var database = require('./database');
database.connect()
.then(function (db) {
app.get('/', function (req, res) {
db.collection(/* … */);
});
})
.catch(function (err) {
console.log('Error connecting to DB:', err);
})
.done();
(我正在使用awesome Q 库。)
(I'm using awesome Q library here.)
下面是我的旧版本回答,为了历史而离开(但如果你不想使用承诺,而不是走那条路,你应该使用马特的回答)。
Below's the old version of my answer, left for the sake of history (but if you don't want to use promises, instead of going that road, you should use Matt's answer).
它的缺点是每当你 require('database.js)$时它会打开一个连接c $ c>(无赖!)
Its downside is that it will open a connection each time you require('database.js)
(bummer!)
// DO NOT USE: left for the sake of history
// database.js
var MongoClient = require('mongodb').MongoClient;
function connect(cb) {
MongoClient.connect(/* the URL */, cb);
}
module.exports = {
connect: connect
}
// app.js
var database = require('./database');
database.connect(function (err, db) {
app.get('/', function (req, res) {
db.collection(/* … */);
});
});
这篇关于如何导出仅在异步回调中可用的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!