Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.preventDefault in async functions

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
}
like image 259
Daniel Herr Avatar asked May 10 '16 18:05

Daniel Herr


People also ask

What does event preventDefault () do?

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.

What is the difference between event preventDefault and event stopPropagation?

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.

Does async await stop execution?

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.

How can we prevent default behavior in react?

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.


1 Answers

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.

like image 102
Bergi Avatar answered Sep 19 '22 08:09

Bergi