以下のコードでは、私は非同期の問題に遭遇していると仮定しています。javascript nodejs if文が予期しない順序で呼び出されています
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文を追加し、最初のif文の最後に同じ関数を呼び出すためにnext()&を追加する必要があると仮定します。
私はまた、メッセージチェックの戻り値が処理される前にelse文が呼び出されていないことを保証するためにnext()を呼び出す必要がありますか? :
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