asynchronous加载NPM模块

我试图创build一个连接到我的数据库(couchDB使用摇篮)的模块。 最后,模块输出“db”variables。

这里是代码:

var cradle = require('cradle'), config = require('./config.js'); var db = new(cradle.Connection)(config.couchURL, config.couchPort, { auth: { username: config.couchUsername, password: config.couchPassword }, cache: true, retries: 3, retryTimeout: 30 * 1000 }).database('goblin'); //database name //Check if DB exists db.exists(function (err, exists) { if (err && exists) { console.log("There has been an error finding your CouchDB. Please make sure you have it installed and properly pointed to in '/lib/config.js'."); console.log(err); process.exit(); } else if (!exists) { db.create(); console.log("Welcome! New database created."); } else { console.log("Talking to CouchDB at " + config.couchURL + " on port " + config.couchPort); } }); module.exports = db; 

问题是,db.exists调用是asynchronous的,如果它不存在,我认为variables导出variables之前完成,影响系统的其余部分。

它以正常的方式包含在执行的节点页面中:

 var db = require('./couchdb.js'); 

有没有办法来防止这种情况发生,或者没有一个巨大的嵌套callback的解决这样的问题的任何最佳做法?

作为参考,你可以在这里看到整个应用程序( https://github.com/maned/goblin ),以及这个项目引用的bug( https://github.com/maned/goblin/issues/36 ) 。

拥抱asynchronous风格。 不是从模块中导出db ,而是导出一个asynchronous函数,如下所示:

 module.exports = { getDb: function(callback) { db.exists(function(err, exists) { if (exists && !err) {callback(db);} else { /* complain */ } }); } }; 

现在应用程序可以只require('mymodule').getDb(appReady)其中appReady接受已知有效且可用的db对象。