0

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

8
  • What version of Node are you running this on? Commented Mar 2, 2018 at 9:09
  • @LukasKnuth v7.10.1 Commented Mar 2, 2018 at 9:11
  • The SyntaxError you're seeing should include additional info like a line-number. Can you mark the line in your code and add the full exception, too? Commented Mar 2, 2018 at 9:13
  • /home/sabin/Work/purchase/napi/api/services/validationService.js:74 const errorMessages = await forms.getErrorMessages('register'); SyntaxError: Unexpected identifier The unexpected identifier is marked at 'forms' Commented Mar 2, 2018 at 9:14
  • When in an async function 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 Commented Mar 2, 2018 at 9:25

1 Answer 1

2

There's no need to create new Promises when you already have a Promise. That is only required when you are converting some API that is not a promise into a promise.

Mongoose can return promises natively too, and the async function will allow any errors that are thrown to bubble up through the promises.

var forms = {

    validation: {
        status: true,
        data: {},
        error: {}
    },

    register: async (data) => {
        var validation = this.validation;
        const errorMessages = await this.getErrorMessages('register');
        ...
    },


    getErrorMessages: async (key) => {
        let contentObj = await Errors.findOne({ type: 'validation', 'identifier': key })
            .select('content')
            .populate('content') // only works if we pushed refs to children
            .exec()

        let errorMessages = {};
        const contentArray = contentObj.content;
        for (var i = 0; i < contentArray.length; i++) {
             let key = contentArray[i].identifier;
             let message = contentArray[i].message;
             errorMessages[key] = message;
        }
        return errorMessages;

    }

};
exports.forms = forms;
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! This worked, it will take a time to understand where the promise should be put and where not...
Whenever you use async you get a new promise, it's not exactly like new Promise as you can't resolve values or reject errors but you can return values and throw errors.
You might still need new Promise when you are converting a stream or callback into a promise, but it's getting rarer
Thanks for the info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.