Reputation: 348
I have a function in NodeJS that makes a query into Mongo. The function is "checkForMatchingEmail".
var result = checkForMatchingEmail(req.body.email);
if ( result === 1) { // something something }
else if ( result === 0) { // something something }
I want to use the RESULT variable for deciding on what to do next. (sending a response to the front-end whether such an e-mail exists in DB).
The problem is that the query to Mongo seems to lag a bit, so the thread just skips over it and the if/else tree is useless, because the query results are not in yet.
What to do?
EDIT:
checkForMatchingEmail looks like this:
function checkForMatchingEmail(email) {
var result = 0;
User.findOne({email: email}, function(err,obj) {
console.log("email is " + email);
if (err) {
return handleError(err);
} else if (obj != null) {
console.log("This email already exists." + obj);
result = 1;
} else if (obj === null) {
result = 0;
console.log("This email does not exist.");
}
});
return result;
}
Upvotes: 0
Views: 156
Reputation: 6898
First of all node.js is asynchronous and evented. There are no threads in this context that could skip over.
When querying mongodb via mongoose you're using a model let's assume User
to execute a query. A typical mongoose query looks something like this
User.find({ email : '[email protected]'}, function(err, user) {
if (err) {
// Do something with the err
}
// Here you have your query result
});
Taking your code example you should extend checkForMatchingEmail
with a callback argument in which you process the result
checkForMatchingEmail(req.body.email, function(result) {
if ( result === 1) { // something something }
else if ( result === 0) { // something something }
});
You might read What is Node.js chapter in Mixu's Node book that explains asynchronous execution in node.js quite well.
Upvotes: 1