Application / JavaScript
Async JavaScript: Fetch, Promises & Errors
Understand promises, async/await, HTTP responses, and complete loading, success, empty, and error states.
What you’ll learn
- Explain asynchronous execution
- Validate HTTP responses
- Design complete request states
Before you start
You’ll need a modern browser, a basic HTML page, and a way to inspect the browser console. Practice with sample data. The interactive guide has its own activities and browser-saved progress.
Understand the idea
An async operation completes later. await pauses that async function, not the entire browser.
fetch resolves for HTTP error responses, so inspect response.ok or status before parsing expected data.
Interfaces need loading, success, empty, and error states. Use AbortController when a request should be cancelable.
Follow the example
async function loadUsers(status, list) {
status.textContent = 'Loading…';
try {
const response = await fetch('/downloads/sample-users.json');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const users = await response.json();
if (!Array.isArray(users)) throw new Error('Expected a list');
list.replaceChildren(...users.map(user => {
const li = document.createElement('li');
li.textContent = user.name;
return li;
}));
status.textContent = users.length ? 'Users loaded.' : 'No users found.';
} catch (error) {
status.textContent = 'Could not load users.';
console.error(error);
}
}An asynchronous request has several visible states: waiting, success and failure. Model those states instead of assuming every request will finish quickly. Await the response, check its status, then parse and validate the data before rendering it. This sample uses a small JSON file on DiscoveryVIP. Call loadUsers with a status element and a list element. If you copy the example to your own server, copy the JSON sample there too and adjust the path.
Try it yourself
Build a safe data viewer. Test success, empty data, invalid URL, slow network simulation, and non-200 response behavior.
Before you run the code, write down the result you expect. Change one input, test a boundary case, and explain why the output changes.
Practice this lesson in the full guide ↗Download the example JSON data ↓
Common mistakes & troubleshooting
- fetch does not reject only because the server returns 404 or 500. Check response.ok explicitly.
- A JSON parse failure may mean the endpoint returned an HTML error page. Inspect the status and content type.
- A slower old response can replace newer results. Use AbortController or a request identifier for search interfaces.
Keep learning
Use your explanation to make a small feature of your own. Review the behavior before connecting it to real user data or a production application.