JavaScript Async/Await and Fetch API
Call an HTTP API, parse JSON and handle network and HTTP errors.
Promises and async
A Promise represents a value that may become available later. An async function returns a Promise, and await pauses that function until it settles.
Fetch JSON data
async function loadUsers() {const response = await fetch('/api/users');
if (!response.ok) throw new Error(HTTP error: ${response.status});
return await response.json();
}
Handle errors
try {const users = await loadUsers();
console.log(users);
} catch (error) {
console.error('Could not load users:', error);
}
A network failure differs from an HTTP 404 or 500. Check response.ok because fetch normally resolves for HTTP error responses.
Send JSON
await fetch('/api/users', {method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Mina' })
});
Consider CSRF protection, credentials policy and server-side validation in authenticated applications.
Practice
Fetch a list, show loading and empty states, render an error message and add a retry action.
Try the concepts in a small project and verify version-specific details with official documentation.
More JavaScript resources