Reputation: 566
I am trying to post to a /user/create route data from a form which all comes through fine and then have it check one by one that the data is valid and in some cases unique in the database. Here is what I am using to check the User and the Email address entered on the registration form.
The function seems to query properly, but in the end, my console.log of the error messages I am collecting is only collecting the first entry.
// 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;
};
Here is where I check the passwords to see if they match.
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;
}
Here is my route with the .then chaining.
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); });
});
I guess where I am struggling is the chaining of .then and how to prevent something from triggering unless everything before it is completed.
Upvotes: 0
Views: 189
Reputation: 204
then()
takes functions as parameters (full specification), but you're passing in promises for your 2nd and 4th .then()
. It should work if you wrap them in anonymous functions instead.
...
.then(function() { return existsInDatabase('userEmail', req.body.email); })
...
.then(function() { return doPasswordsMatch(req.body.password, req.body.confirmedPassword); })
...
return
is so the promises returned by existsInDatabase()
and doPasswordsMatch()
are resolved before moving on to the next then()
However, you may need to rethink the way your logic is set up. The way it is currently, if the passwords do match, the next .then
is never called, and the logic just gets stuck.
Upvotes: 1