Here is an example for querying user from database then if user exists, another query for phone:
module.exports = function (username, req, res, next) {
var query = User.where('username', new RegExp('^' + username + '$', 'i'));
query.findOne(function (err, user) {
if (err) {
res.send("error");
//## position D
} else if (!user) {
res.send("user not found");
//## position D
} else {
//user exists
//search for phone
var query2 = Phone.where('phone', new RegExp('^' + user.phone + '$', 'i'));
query2.findOne(function (err, phone) {
if (err) {
res.send("error");
//## position D
} else if (!phone) {
res.send("phone not found");
//## position D
} else {
res.send(phone);
//## position D
}
//## position C
});
}
//## position B
});
//## position A
}
My question is: based on this code, where is the correct place to set return next(); ? and why ?
I set some proposals:
Position A: @ the bottom of function. here it would be called even earlier than querying data from database
Position B: @ the bottom of 1st callback function
Position C: @ the bottom of last callback function
Position D: after res.send(..) immediately
P.S: I know that I can pass error as object inside next.. I just want to make code simple to focus on the main issue.
Thanks yokefellows,'.