Handle clicks and API calls: events, fetch, and async/await.
Handle clicks and API calls: events, fetch, and async/await.
Lesson outline
The browser is event-driven: user clicks, form submits, and the page loading all fire events. Your code reacts with handlers. Data often comes from the network, which is slow and asynchronous.
You need two things: a way to listen for events and a way to handle async work (e.g. fetch) without blocking the UI. The event loop and Promises tie these together.
addEventListener(type, handler) attaches a handler to an element (click, submit, keydown, load, etc.). preventDefault() and stopPropagation() control default behavior and bubbling.
The event loop runs in a single thread. When you start fetch or setTimeout, the browser does the work in the background and runs your callback when it is ready. That is why you never block the UI while waiting for the network.
Event loop in one line
One thread: your code runs, then the browser runs callbacks when fetch/timeout is ready. No blocking.
fetch(url, { method, headers, body }) returns a Promise that resolves to a Response. Check response.ok (or status code), then response.json(), .text(), or .blob(). Always handle loading, success, and error in the UI.
For authenticated APIs, send Authorization: Bearer <token> or rely on cookies. If the API is on another origin, the server must send CORS headers or the browser blocks the response. Store tokens safely (e.g. httpOnly cookie); handle 401 by re-auth or refresh.
async functions return Promises; await pauses until the Promise settles. Use try/catch for errors. Code reads like synchronous flow: await fetch, then await response.json(), then use the data.
Await only works inside async functions. At the top level (e.g. in a module) you can use top-level await where supported. [MDN – Dynamic scripting](https://developer.mozilla.org/en-US/docs/Learn_web_development/Getting_started) (Events, Network requests).
Key takeaways
Related concepts
Explore topics that connect to this one.
Ready to see how this works in the cloud?
Switch to Career Paths for structured paths (e.g. Developer, DevOps) and provider-specific lessons.
View role-based pathsSign in to track your progress and mark lessons complete.
Questions? Discuss in the community or start a thread below.
Join DiscordSign in to start or join a thread.