I'm currently working on a validation module in nodeJs and I cannot seem to understand how or why does the async/await does not work in my current module.
In the module I should be able to have more than one validation exports ex: Forms, Data etc.
Each object should have more that one validation functions, ex: forms should have register, login, add etc...
This is my approach
var forms = {
validation: {
status: true,
data: {},
error: {}
},
register: async(data) => new Promise((resolve, reject) => {
var validation = forms.validation;
try {
const errorMessages = await forms.getErrorMessages('register');
...
} catch (error) {
reject(error);
}
}),
getErrorMessages: (key) => new Promise((resolve, reject) => {
Errors.
findOne({ type: 'validation', 'identifier': key }).
select('content').
populate('content'). // only works if we pushed refs to children
exec(function(err, contentObj) {
if (err) reject(err);
var errorMessages = {};
const contentArray = contentObj.content;
for (var i = 0; i < contentArray.length; i++) {
var key = contentArray[i].identifier,
message = contentArray[i].message;
errorMessages[key] = message;
}
resolve(errorMessages);
});
}),
};
exports.forms = forms;
Now at the register function, which is defined as async function, in try I have that await forms.getErrorMessages('register') which should return the validation error messages from the database... The function works, it's defined to return a promise but I always get SyntaxError: Unexpected identifier for the function...
Can anyone explain why this doesn't work?
Thanks
asyncfunction you don't need to create a new promise unless you are resolving a callback. Mongoose can return promises as well, so you don't need to use it's callback interface either