Will it be possible to use event.preventDefault in an async function?
I am not sure because event.preventDefault must be called synchronously and async functions return promises.
self.oncontextmenu = async function(event) {
event.preventDefault()
//await whatever
}
Event.preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
stopPropagation prevents further propagation of the current event in the capturing and bubbling phases. preventDefault prevents the default action the browser makes on that event.
async functions use an implicit Promise to return results. Even if you don't return a promise explicitly, the async function makes sure that your code is passed through a promise. await blocks the code execution within the async function, of which it ( await statement ) is a part.
We can prevent this default behaviour by making a small modification to the definition of the handleSubmit function. We call a preventDefault on the event when submitting the form, and this will cancel the default event behavior (browser refresh) while allowing us to execute any code we write inside handleSubmit.
Yes, it is totally possible to call preventDefault()
in an async
event handler function
. You only have to ensure to make the call before the first await
, as otherwise the event already will have happened when the function resumes. The event flow will continue and not wait for the promise that the event handler returns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With