使用asynchronous队列来控制数据库连接请求

我使用Node anb Mongodb Native构build应用程序。 我正在处理一个数据库模块,我可以要求和调用其他模块,以便我最终只使用一个连接。 模块db.js从这个代码开始:

 var _db = null; var getDb = module.exports.getDb = function(callback) { if (_db) { console.log('_db returned'); return callback(null, _db); } MongoClient.connect('mongodb://localhost:' + config.db.port + '/' + config.db.name, {native_parser: true}, function (err, db) { if (err) return callback(err); console.log('_db created'); _db = db; callback(err, _db); }); }; 

在我需要数据库连接的其他模块中,我这样做

 db.getDb(function (err, connection) { // Do something with connection }); 

它工作正常。 但一个令人不快的问题是,如果我的代码会在很短的时间内多次调用getDb ,那么我最终会getDb多个连接的副本。 就像我在所有需要数据库连接的模块的最开始执行db.js要求和getDb调用一样

我现在考虑通过排队来控制getDb的调用,这样只有绝对的第一次调用才会创build一个连接并将其保存在_db 。 以后的所有调用都会得到所创build的连接_db 。 我相信asynchronous队列将帮助我与此…

问题是 ,我不明白我如何写与asynchronous队列。 该文件有点含糊,我没有find更好的例子在线。 也许你可以给我一些提示。 这是我到目前为止…

 var dbCalls = async.queue(function (task, callback) { if (_db) { console.log('_db returned'); return callback(null, _db); } MongoClient.connect('mongodb://localhost:' + config.db.port + '/' + config.db.name, {native_parser: true}, function (err, db) { if (err) return callback(err); console.log('Connected to mongodb://localhost:' + config.db.port + '/' + config.db.name); _db = db; callback(null, _db); }); }, 1); // I guess this .push() must be the exposed (exported) API for other modules to get a connection, but how do I return it to them, dbCalls.push(null, function (err) { console.log('finished processing foo'); }); dbCalls.push(null, function (err) { console.log('finished processing bar'); }); 

我不明白作为第一个parameter passing给对象.push()我应该如何使用? 现在它的null如何将连接和可能的错误传递给发出调用的模块?

没有async.queue快速和肮脏的解决scheme:

 var _db = null; var _err = null; var _queue = []; var _pending = false; var getDb = module.exports.getDb = function(callback) { if (_err || _db) { console.log('_db returned'); return callback(_err, _db); } else if (_pending) { // already a connect() request pending _queue.push(callback); } else { _pending = true; _queue.push(callback); MongoClient.connect(..., function (err, db) { _err = err; _db = db; _queue.forEach(function(queuedCallback) { queuedCallback(err, db); }); }); };