Returning an awaited function in onsubmit is always submitting the form

I want the form to be prevented submitting if the result is false. But the form is always getting submitted even when the result is false.

<form onsubmit="let result = await foo(); return result;">
let foo = async() =>
{    
    // await fetch(url) and get some result which may be either true or false

    return result;
}

onsubmit start foo and return false. Have foo await the fetch and then submit the form.

await doesn’t block the code, it makes the function return a promise. So what’s going to happen is your onsubmit handler will return a promise, the browser will check that and determine it is a truthy value and submit the form.

If you need to delay the submission through some asynchronus process like await, then you need to simply cancel the submission and after your process completes re-submit the form if everything is ok.

First, stop using the onsubmit attribute in your HTML and switch to the addEventListener function.

<form id="myForm">
const form = document.getElementById('myForm');
form.addEventListener('submit', async function(e){
    e.preventDefault();
    const result=await fetch(url);
    if (result.ok){
       const data=await result.json();
       if (data.whatever){
            form.submit();
       }
    }
});

The function gets the event as it’s first argument when called by addEventListener. Calling the preventDefault method on that event object stops the form submission. Next you do whatever asynchronous process you need and if everything is ok, call the form’s submit() method to re-submit the form.

If you don’t want the form to submit at all, then just call preventDefault() and do your stuff, leave out the call to submit().

3 Likes