Return value is ignored: Event handlers don't use the returned Promise, so the browser won't wait for your async operations to complete before moving on.
Error handling: Always use try/catch blocks in async event handlers because unhandled rejections won't be caught by the normal event system.
Event timing: If you need to call methods like event.preventDefault(), do it synchronously before any await statements:
javascript
form.addEventListener('submit', async (event) => {
event.preventDefault(); // Call this before await
const formData = new FormData(event.target);
await submitForm(formData);
});
Multiple async operations: The event handler will return immediately after hitting the first await, so multiple async handlers can run concurrently:
This pattern is particularly useful for handlers that need to make API calls, read files, or perform other asynchronous operations.
User
Does preventDefault work?
Assistant
Yes, preventDefault() works in async event handlers, but you need to call it synchronously before any await statements.
Here's the key difference:
✅ This works:
javascript
form.addEventListener('submit', async (event) => {
event.preventDefault(); // Called immediately, before await
const data = await fetchData();
// ... rest of async code
});
❌ This doesn't work:
javascript
form.addEventListener('submit', async (event) => {
const data = await fetchData(); // Too late!
event.preventDefault(); // Browser already processed the default action
});
The reason is that preventDefault() must be called during the initial synchronous phase of event handling. Once you hit an await, the function returns a Promise and the browser continues with its default behavior (like submitting the form or following a link).
This applies to other synchronous event methods too: