我正在尝试创建一个连接到我的数据库的模块(使用 Cradle 的 couchDB)。最后,模块导出“db”变量。
代码如下:
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 调用是异步的,如果它不存在,我认为变量会在完成之前导出变量,从而影响系统的其余部分。
它以正常方式包含在执行的 Node 页面中:
var db = require('./couchdb.js');
有没有办法防止这种情况发生,或者有什么最佳实践可以在没有巨大的嵌套回调的情况下解决这样的问题?
作为引用,您可以在此处 (https://github.com/maned/goblin) 查看整个应用程序,并在此处 (https://github.com/maned/goblin/issues/36) 查看项目引用的错误。
最佳答案
拥抱异步风格。不是从模块中导出 db
,而是像这样导出一个异步函数:
module.exports = {
getDb: function(callback) {
db.exists(function(err, exists) {
if (exists && !err) {callback(db);} else { /* complain */ }
});
}
};
现在应用程序可以只require('mymodule').getDb(appReady)
其中 appReady
接受一个已知的 db
对象有效且可用。
关于javascript - 异步加载 NPM 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20666150/