나는이 같은 싱글 톤을 권장하지 않습니다. 의존성 삽입은 더 나은 해결책이며, 응용 프로그램 당 연결은 거의 확장 할 수 없습니다. 연결 풀이 더 좋은 아이디어 일 수 있습니다.
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
});
};
}
'다음'을 살펴보십시오. [이 질문과 답변] (http://stackoverflow.com/q/8710669/1348195)을 참조하십시오. –
어디에 건네 주시겠습니까? – giodamelio
'.next'를 호출하여 데이타베이스 연결이 끝나면 완료되었음을 알립니다. –