Async JavaScript and APIs
💻 JavaScriptFetch data from an API with promises and async/await, then handle errors.
Some work takes time: network requests, timers and file reads. Asynchronous code lets the page keep responding while it waits.
- Explain a promise.
- Use fetch with async/await.
- Handle loading and error states.
Promises
A promise represents a value that will arrive later. It can be pending, fulfilled or rejected. fetch returns a promise.
Fetch with async/await
Mark the function async and use await to pause until the promise settles.
async function loadUsers() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const users = await response.json();
console.log(users);
} catch (error) {
console.error("Could not load users:", error.message);
}
}
loadUsers();Loading and Error States
A real interface shows a loading message, then either data or an error. Never leave the user staring at a blank screen.
const status = document.querySelector("#status");
async function loadPosts() {
status.textContent = "Loading…";
try {
const response = await fetch("/api/posts");
if (!response.ok) throw new Error("Server error");
const posts = await response.json();
status.textContent = `${posts.length} posts loaded`;
} catch (error) {
status.textContent = "Could not load posts. Please try again.";
}
}Practice
- Fetch a list of posts and log the titles.
- Show a loading message while the request runs.
- Display a friendly error if the request fails.
Hands-on exercise
Write an async function that fetches https://jsonplaceholder.typicode.com/todos/1 and logs the title.
Handle errors with try/catch.
Recap
Promises represent future values. async/await makes them readable, and try/catch keeps failures from breaking the page.
Example
async function loadUsers() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const users = await response.json();
console.log(users);
} catch (error) {
console.error("Could not load users:", error.message);
}
}
loadUsers();
Exercises
Handle errors with try/catch.
Expected Output
The title of the todo is printed to the console.