Fetching the image list
Fetch an image list from an API with async/await and parse it as JSON.
async/await with fetch
Inside an async function we use await to wait for a fetch call. fetch(url) returns a Response object; on success response.ok is true.
The flow is:
- wait for the request with
const response = await fetch(url) - check for errors with
if (!response.ok) - read the body with
await response.text()
We'll wrap this pattern in a function named fetchImages.
Catching errors with try/catch
Network requests can fail for many reasons: a wrong address, a dropped connection or a server error. If an await call wrapped in a try block throws, control jumps to the catch block.
For example:
try {
const response = await fetch(url);
} catch (error) {
console.log(error.message);
}This way the app catches the error instead of crashing.
Exercise Write the fetchImages function
Continue on top of the previous lesson's solution. Write an async function named fetchImages that takes a url parameter. Inside a try block, get the response with const response = await fetch(url); if if (!response.ok), throw new Error('HTTP ' + response.status). Then return await response.text() to return the body. In a catch (error) block, log the error with console.log(error.message).
Show example solution
Start with async function fetchImages(url), do the fetch and response.ok check in a try block, return await response.text(), and log the error with console.log in catch (error).
Example solution:
// Gallery application
const app = document.getElementById("app");
const title = document.createElement("h1");
title.textContent = "Gallery";
app.appendChild(title);
const gallery = document.createElement("div");
gallery.className = "gallery";
app.appendChild(gallery);
const images = [
{ url: "https://picsum.photos/id/1/200/200", title: "Mountain view", author: "Alex" },
{ url: "https://picsum.photos/id/2/200/200", title: "City streets", author: "Mark" },
{ url: "https://picsum.photos/id/3/200/200", title: "Lakeside", author: "Zoe" }
];
async function fetchImages(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return await response.text();
} catch (error) {
console.log(error.message);
}
}
Test yourself
-
What does await do?
const response = await fetch(url);- It cancels the request
- It caches the response
- It waits until the Promise resolves
- It turns the response into a string
Show answer
It waits until the Promise resolves — Correct! await pauses the function until the Promise resolves.
-
Complete the response.ok check
if (____) { throw new Error('HTTP ' + response.status); }Show answer
if (!response.ok) { throw new Error('HTTP ' + response.status); } -
Match the API concepts
- async
- Function returning a Promise
- await
- Keyword that waits
- fetch
- Function making a request
- response.ok
- Success status
- throw
- Raising an error