让一些构造函数同步运行会很不错。考虑以下DAO模块:
var MongoClient = require('mongodb').MongoClient;
FooDao = function(mongoUrl) {
var self = this;
MongoClient.connect(mongoUrl, function(err, database) {
if(err) throw err;
self.foos = database.collection("foos");
})
};
FooDao.prototype.findById = function(id, callback) {
this.foos.findOne({"id": id}, callback)
};
FooDao.prototype.save = function(foo, callback) {
this.foos.update({"id":foo.id}, foo, {upsert:true, w: 1}, callback)
};
exports.FooDao = FooDao;
其用户可能包含以下代码:
var FooDao = require('./foo-dao').FooDao;
var fooDao = new FooDao(mongoUrl);
fooDao.findById(42, function(err, foo) {
if (!err) console.log(foo);
});
此代码立即失败,因为FooDao
尚未完成与MongoDB的连接。
有没有办法实现FooDao
构造函数来使代码通过?