Understand Asynchronous JavaScript with Practical Examples
Use promises and async/await to build a data request with loading, success, empty and error states.
Introduction
Network requests finish later than the code that starts them. JavaScript represents that future result with a promise. Async and await make promise-based control flow easier to read, but they do not remove failure, delay or cancellation. A dependable interface treats each visible state as part of the feature.
How the topic works
An async function returns a promise. Await pauses that function until the promise settles while the browser can continue other work. Place request code in try and catch, but also check the HTTP status because a completed fetch can still be an error response. Update the interface deliberately before and after the request.
Practical workflow
- Render a loading message and temporarily disable the request button.
- Start fetch with a timeout or cancellation signal where supported.
- Check response.ok before parsing the expected JSON shape.
- Validate the parsed fields and render success or empty content safely.
- Catch failures, show a useful retry message and restore the button in finally.
Tools and technologies
- Browser Fetch API
- Developer Tools network panel
- A local or approved sample JSON endpoint
Example
A study-topic viewer requests an array of topics. A 200 response with an empty array shows βNo topics available,β malformed data shows a controlled format error, and an unavailable service shows a retry button rather than leaving a permanent spinner.
Common mistakes
- Assuming fetch rejects for every HTTP error status
- Showing raw exception details to users
- Updating the page after an obsolete request finishes
Security and best practice
Insert external text with textContent rather than HTML. Limit request frequency, validate response shape and avoid placing credentials in browser JavaScript.
Portfolio task
Key takeaways
- Async code needs explicit interface states.
- HTTP completion is not the same as success.
- External data remains untrusted after parsing.
