I have an asynchronous problem here. The forEach is still running when res.json({ errors }); returns so all the errors aren't picked up. How do I deal with this?
router.post('/new/user', async function (req, res, next) {
const validateEmail = async (email) => {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
const reqBody = { email, password };
let errors = {};
Object.keys(reqBody).forEach(async (field) => {
if (field === 'email' && validateEmail(await reqBody[field])) {
errors = { ...errors, [field]: 'Not a valid Email' };
}
console.log(3);
if (field === 'password' && password !== '' && password < 4) {
errors = { ...errors, [field]: 'Password too short' };
}
});
if (Object.keys(errors).length > 0) {
res.json({ errors });
}
}
.forEach()loop wait for an asynchronous operation inside of it. It just isn't designed to work that way. Instead, you can use a plainforloop withawaitinside the loop. IMO,.forEach()should be ditched permanently. Regularforloops are so much more powerful these days and easier for the interpreter to optimize too.for(let i=0; i<Object.keys.length; i++){ if(i===email){} . . . }Use this, It will work.