I am trying to understand the behavior of async
functions and Joi.validate()
function. Below is the function I am using to validate user's input.
const Joi = require("joi");
const inputJoiSchema= Joi.object().keys({
name: Joi.string(),
email: Joi.string().required(),
password: Joi.string().required()
});
function validateUser(body) {
return Joi.validate(body, inputJoiSchema);
}
module.exports = validateUser
validateUser
returns proper validate object
{
error:<error/null>,
value:<value/null>,
then: [Function: then],
catch: [Function: catch] }
but for any reason, If I change validateUser function to async function like below it returns Promise instead of object.
async function validateUser(body) {
return Joi.validate(body, inputJoiSchema);
}
Why so? I am not passing any callback function to Joi.validate and my route handling function looks like below.
router.post("/", async (req, res) => {
result = validateUser(req.body);
if(result.error){
res.status(400).send("Invalid request")
}
<some other steps I do after validating>
}