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.
Add a list to the page before running the script:
<ul id="items"></ul>
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.table(items);
const list = document.querySelector("#items");
list.replaceChildren(...items.map((item) => {
const row = document.createElement("li");
row.textContent = item.name;
return row;
}));
} catch (error) {
console.error("Could not load items:", error);
}
}
loadItems();
The request above reads the sample items.json file stored beside this lesson. Its JSON response is an array of objects, so console.table() displays the returned rows in the browser developer console.
What async and await mean
An async function always returns a promise. Inside it, await waits for one promise to settle before that function continues; it does not freeze the whole page. Use it when the next step depends on the previous result. In a regular script, write await inside an async function; top-level await is available in JavaScript modules.
Handle failures
The try...catch block handles network errors and errors thrown when the response status is not successful. The example uses a same-origin file. If you replace it with another domain, that server may need to allow cross-origin requests.
Display returned text safely
The request example uses textContent to display each item's name as text. When fetched values may come from users or another untrusted source, avoid inserting them with innerHTML; the browser would parse that string as markup.
Run independent requests together
If two requests do not depend on each other, start both before awaiting either one. Promise.all() waits for all results and rejects if any one promise rejects; use it when all results are required. Replace these sample URLs with endpoints available to your project.
async function loadDashboard() {
const [profileResponse, settingsResponse] = await Promise.all([
fetch("/api/profile"),
fetch("/api/settings")
]);
for (const response of [profileResponse, settingsResponse]) {
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
}
return Promise.all([
profileResponse.json(),
settingsResponse.json()
]);
}
Calling await separately for each independent request would make them run one after another, which can take longer. The function above still checks both HTTP statuses before reading either response body.
Read MDN's guides to async functions and the Fetch API for more detail.