JavaScript Async and Await with Fetch
Learn JavaScript async and await, fetch JSON data, check HTTP responses and handle request errors.
Why asynchronous code is useful
A network request takes time. JavaScript can continue running other work while it waits for a response. An async function lets you use await to write that sequence clearly.
Request and read JSON
fetch() returns a promise. Check response.ok because an HTTP error status does not by itself make the promise reject.
async function loadItems() {
try {
const response = await fetch("/data/items.json");
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const items = await response.json();
console.log(items);
} catch (error) {
console.error("Could not load items:", error);
}
}
loadItems();
Handle failures
The try...catch block handles network errors and errors thrown when the response status is not successful. Replace the example path with a URL your page is allowed to request.
A browser request to another domain may require that server to allow cross-origin requests. Do not place secret API keys in front-end JavaScript.