我建議不要這樣的單例,依賴注入是一個更好的解決方案,每個應用程序的連接幾乎不可擴展。連接池可能是一個更好的主意。
這就是說,你可以這樣做:
var db = null; // to keep our instance
var asked = false; // to not make several requests that override each other
function openDb(db,ready){
// if we already have it, we return the instance
if(db !== null) ready(null,db);
// if it was already asked by another instance, keep track of it
// to avoid multiple requests.
if(asked) asked.push(ready);
asked = [];
openDbCode(db,function(err,result){
if(err) {
ready(err,null); // error case
asked.forEach(function(fn){ fn(err,null); }); // notify waiters of failure
}
db = result; // save the reference
asked.forEach(function(fn){ fn(db,null); }); // notify all waiters
})
}
此功能有效地等待第一個提問者分貝然後調用同一個實例大家。請注意,該函數將使用提供的第一個連接字符串。
module.exports = function(db) {
return function(req, res, next) {
openDb(db,function(err,db){
if(err) handleDbOpenErrorLogicHere();
// middleware stuff, same db available here, call next to continue
});
};
}
看看傳遞'next',看看[這個問題和答案](http://stackoverflow.com/q/8710669/1348195)如何。 –
將它傳遞到哪裏? – giodamelio
在完成連接到數據庫之後,調用'.next'來表示完成。 –