I've spent a couple of hours trying to get the below Async request working correctly, and after learning a whole bunch about Async requests, mongoose, and node.js, it turns out my issue was more or less a syntax problem (as I can understand it).
Can anyone tell me why this code works, but my original code doesn't?
Working Code:
router.get('/usercheck', function(req, res) {
var usr = Person.findOne({username: req.query.u}, function(err, user){
if(user != null){
return user
}else return null
})
var eml = Person.findOne({email: req.query.e}, function(err, user){
if(user != null) {
return user
}else return null
});
var resolve = function(e, u){
if(e === null && u === null) res.sendStatus(200) //Both available
else if (e === null && u != null) res.sendStatus(409) //"Email free, user taken"
else if (e != null && u === null) res.sendStatus(403) //"Email taken, user free"
else if (e!=null && u!=null) res.sendStatus(418) //"Email and user taken"
else res.sendStatus(500) // Something broke, no idea what
}
async function handler() {
const user = await usr;
const email = await eml;
return resolve(email, user);
}
handler();
});
Original Code:
router.get('/usercheck', function(req, res) {
function usr() {
Person.findOne({username: req.query.u}, function(err, user){
if(user != null){
return user
}else return null
})
}
function eml(){
Person.findOne({email: req.query.e}, function(err, user){
if(user != null) {
return user
}else return null
});
}
var resolve = function(e, u){
if(e === null && u === null) res.sendStatus(200) //Both available
else if (e === null && u != null) res.sendStatus(409) //"Email free, user taken"
else if (e != null && u === null) res.sendStatus(403) //"Email taken, user free"
else if (e!=null && u!=null) res.sendStatus(418) //"Email and user taken"
else res.sendStatus(500) // Something broke, no idea what
}
async function handler() {
const user = await usr();
const email = await eml();
return resolve(email, user);
}
handler();
});
I'm sure there is a logical reason for this, but I don't understand it atm. In so far as my understanding goes, the return statement in either version of the code should get passed to resolve(), which should evaluate it.
However, with the second, original implementation, nothing gets passed to resolve() at all, the if else loop fails, and fall back error 500 is sent; Can anyone help me understand why?