Учитывая приведенный ниже код, я предполагаю, что у меня проблема с асинхронным доступом.javascript nodejs, если операторы вызывают в непредвиденном порядке
exports.existingCheck = function (req, res, next) {
var query = [],
message = [],
userObj = {},
i, body = req.body;
if(body.displayName){
var regex = new RegExp(["^", body.displayName, "$"].join(""), "i");
};
if(req.user){
var userObj = req.user;
}
if (body.displayName !== userObj.displayName) {
console.log('body n no match')
query.push({
displayName: regex
});
}
if (body.email !== userObj.email) {
console.log('body e no match')
query.push({
email: body.email
});
}
console.log('query pre ', query)
if (query.length) {
console.log('query init ', query)
//find a match for email or display name and send appropriate error message;
User.find({
$or: query
},
function (err, existing) {
if (err) {
console.log('register er ', err)
}
if (existing.length) {
for (i = 0; i < existing.length; i++) {
var conditional1 = false, conditional2 = false;
console.log('conditional1 init ', conditional1)
if(body.displayName && (userObj._id !== existing[i]._id)){
conditional1 = body.displayName.toLowerCase() === existing[i].displayName.toLowerCase();
};
console.log('conditional1 after ', conditional1)
if(body.email && (userObj._id !== existing[i]._id)){
conditional2 = body.email.toLowerCase() === existing[i].email.toLowerCase();
}
if (conditional2) {
message.push('Email is not unique.');
}
if (conditional1) {
message.push('Display name has already been taken.');
}
}
}
});
}
console.log('message check ', message)
if (message.length) {
return res.status(409).send({
'message': message
});
}
console.log('next')
next();
};
код ниже результатов в console.logS стреляющих в таком порядке:
body n no match
query pre [ { displayName: /^bobohead$/i } ]
query init [ { displayName: /^bobohead$/i } ]
message check []
next
conditional1 init false
conditional1 after true
С решаемой, что условными не не получают свои значения, пока после проверки сообщения и следующий() являются вызывается.
Я думал, что утверждения if блокируют код и что один будет ждать, пока другой будет запущен.
Я предполагаю, что мне нужно будет добавить оператор else для вызова функции, которая вызывает проверку сообщения и next() &, чтобы вызвать ту же самую функцию в конце инициализации if.
Мне также нужно убедиться, что я вызываю next() в выражении else, чтобы убедиться, что он не вызывается до того, как обработана обратная проверка сообщения? :
console.log('message check ', message)
if (message.length) {
return res.status(409).send({
'message': message
});
}
else{
console.log('next')
next();
}
};
И в чем проблема в точности? это то, что 'console.log' всегда регистрирует' {displayName:/^ bobohead $/i} '? –
Нет, что условные выражения не вызываются до следующей() или проверки сообщений/ошибок. – NoobSter