17

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
}
Daniel Herr
  • 19,083
  • 6
  • 44
  • 61
  • 2
    You cannot use `preventDefault` async, because the event handling is fully synchronous. (similar question: [Problems with e.preventDefault()](http://stackoverflow.com/questions/6100826) ) – t.niese May 10 '16 at 18:32
  • perhaps you should give a more concrete example of what you are trying to do. I'm not sure I understand your goal, and I have the impression you are mixing up things a bit. Also promise and async are two different things (though related) – Pevara May 10 '16 at 18:35

1 Answers1

30

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    (There are experiments with "[ExtendableEvent](https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent)s" that can be made to wait for *some* promises, but they're not DOM events and they don't have to do anything with `async function`s) – Bergi May 10 '16 at 19:03
  • Well, there goes my super duper idea for using an (asynchronous) Bootstrap modal instead of a (synchronous) confirm(). – Ron Inbar May 20 '20 at 12:24
  • 2
    @RonInbar Depending on what event you are trying to prevent, you may just always call `preventDefault()` (as the default action should not happen right now), show your asynchronous modal, and when the user confirms that (by a different event) you can trigger the original action directly. – Bergi May 20 '20 at 12:32