在 for 循环中匹配条件后函数执行不会停止
Function execution is not stopping after matching condition in for-loop
my node req and res, I want to stop execution after matching condition, however its doing whole operation pushing array and sending double response
Router.post('/api/friend-req', async (req, res)=>{
try{
let newDate = new Date().toISOString();
const bodyData = req.body;
let requestList = await User.findOne({_id:bodyData.friend_id}, ['requests']);
for(var i = 0; i < requestList.requests.length; i++){
if(requestList.requests[i].friend == bodyData.user_id){
await res.json({error:'requests alreay sent'});
break;
//its doing below operation even after matching my codition and sending double response
};
};
//this will be done only when condition does not match
requestList.requests.push({
friend: bodyData.user_id,
addAt: newDate
});
const storeUser = await User.findOneAndUpdate({_id:bodyData.friend_id}, {requests: requestList.requests});
res.json({success:'req sent successfuly'});
}catch(err){
console.log(err);
res.status(400).json(err);
}
});
尝试
return res.json({error:'requests alreay sent'});
my node req and res, I want to stop execution after matching condition, however its doing whole operation pushing array and sending double response
Router.post('/api/friend-req', async (req, res)=>{
try{
let newDate = new Date().toISOString();
const bodyData = req.body;
let requestList = await User.findOne({_id:bodyData.friend_id}, ['requests']);
for(var i = 0; i < requestList.requests.length; i++){
if(requestList.requests[i].friend == bodyData.user_id){
await res.json({error:'requests alreay sent'});
break;
//its doing below operation even after matching my codition and sending double response
};
};
//this will be done only when condition does not match
requestList.requests.push({
friend: bodyData.user_id,
addAt: newDate
});
const storeUser = await User.findOneAndUpdate({_id:bodyData.friend_id}, {requests: requestList.requests});
res.json({success:'req sent successfuly'});
}catch(err){
console.log(err);
res.status(400).json(err);
}
});
尝试
return res.json({error:'requests alreay sent'});