나는/user /에 모든 데이터를 유효하게 그리고 어떤 경우에는 데이터베이스에서 유일하다는 점을 하나씩 확인하도록 폼에서 라우트 된 데이터를/user /에 게시하려고한다. 다음은 등록 양식에 입력 된 사용자 및 이메일 주소를 확인하기 위해 사용하는 것입니다.이전의 명령문이 완료되기를 기다리지 않을 것이라고 약속합니다.
이 함수는 제대로 쿼리하는 것처럼 보이지만 결국에는 수집하고있는 오류 메시지 중 console.log에 첫 번째 항목 만 수집됩니다.
// Check if variable is already is available or not
var existsInDatabase = function(field, value){
var deferred = Q.defer();
var query = {};
var errorMessage = {};
query[field] = value;
User.find(query, function(err, docs){
// If it finds it, then set a message for already existing
if(docs){
errorMessage = {'type': 'alert', 'body': value + ' already exists in the database.'}
deferred.resolve(errorMessage);
} else {
deferred.reject(value + ' was not found in the database');
}
});
return deferred.promise;
};
여기서 내가 일치하는지 확인하기 위해 암호를 확인합니다.
var doPasswordsMatch = function(password, confirmed){
var deferred = Q.defer();
console.log('Values passed into doPasswordsMatch() function:', password + ' ' + confirmed);
if(password !== confirmed){
errorMessage = {'type': 'alert', 'body': 'The two passwords you entered do not match'};
deferred.resolve(errorMessage);
};
return deferred.promise;
}
다음은 .then 체인을 사용하는 경로입니다.
router.post('/user/create', function(req, res){
var errorMessages = [];
existsInDatabase('userName', req.body.username)
.then(function(errorMessage){ if (errorMessage) { errorMessages.push(errorMessage) } })
.then(existsInDatabase('userEmail', req.body.email))
.then(function(errorMessage){ if (errorMessage) { errorMessages.push(errorMessage) } })
.then(doPasswordsMatch(req.body.password, req.body.confirmedPassword))
.then(function(errorMessage){ if (errorMessage) { errorMessages.push(errorMessage) } })
.then(function(){ console.log(errorMessages); });
});
내가 고민하는 곳은 .then의 연결 고리이며, 모든 것이 완료되기 전에 트리거링을 방지하는 방법입니다.
왜 때로는 함수를 전달하고 때로는 '다음'을 약속합니까? '.then (console.log (errorMessages))'가 작동 할 것으로 기대하십니까? – Bergi