异步加载 NPM 模块

Asynchrously load NPM module

本文关键字:模块 NPM 加载 异步      更新时间:2023-09-26

我正在尝试创建一个连接到我的数据库的模块(使用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 调用是异步的,如果它不存在,我认为变量会在完成之前导出变量,从而影响系统的其余部分。

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

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对象的位置。