0

So I am doing a basic validation in my React App. I am using react-final-form and what the validation does it returns an object of errors, if they exists. For one set of my validation I am using an async function and it always returns Promise{<pending>}. I am not sure why because all my await methods are closed with a .then(); Please have a look at my code:


async function checkEmail(email) {
    const result = await axios
            .post(`/api/check-email`, { values: email })
            .then(e => e.data.exists);
            
    return result;
}

// main validation object
const validation: async values => {
        const errors = {};

        if(!values.email) {
            errors.email = "Email is required"
        } else {
            const response = await checkEmail(values.email).then(e => { return e; });
            if(response) {
                errors.email = "Email taken!"
            }
        }

        return errors;
    }

Once the email is validated and if the response returns false the validation should return an empty object like {} however it returns Promise {<pending>}.

Thank you!

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
Eddsters
  • 458
  • 1
  • 4
  • 16
  • `async` function will always return a `Promise`. It implicitly wraps your `errors` into a `Promise` before returning it. – Lakshya Thakur Mar 21 '21 at 19:43
  • @LakshyaThakur Thank you so how can i resolve it so instead of a promise I acutally return the object ? – Eddsters Mar 21 '21 at 19:43
  • https://stackoverflow.com/questions/49982058/how-to-call-an-async-function/49982214#49982214 – Taki Mar 21 '21 at 19:44
  • 2
    @Eddsters Either use `validation(values).then((err)=>..)` or `const errors = await validation(values)` inside another `async` function. – Lakshya Thakur Mar 21 '21 at 19:46
  • It is okay to have an async validation function (one which returns a promise) in react-final-form. Try it! `
    { const errors = {} if(!values.email) { errors.email = "Email is required"; } else { const taken = await checkEmail(values.email); if(taken) { errors.email = "Email taken!" } } return errors; }}`
    – Linda Paiste Mar 22 '21 at 00:04

0 Answers0