Understanding Fetch - Exercises
Five exercises to make sure everything clicks before moving into CRUD.
Exercise 1 - Arrow Functions
Rewrite all four of these as arrow functions:
function triple(n) {
return n * 3
}
function fullName(first, last) {
return first + " " + last
}
function isEven(n) {
return n % 2 === 0
}
function shout(text) {
let upper = text.toUpperCase()
return upper + "!"
}
Call each one with a test value and log the result to confirm it works.
Exercise 2 - Your First Fetch
Write a fetch call that loads a single post from https://jsonplaceholder.typicode.com/posts/1.
Use arrow functions. When the data arrives, log the title and body fields separately.
Exercise 3 - Adding Error Handling
Take the fetch call from Exercise 2 and add .catch() to it. The catch should log the error message to the console.
Then test it - change the URL to https://jsonplaceholder.typicode.com/notarealpath and confirm your .catch() fires.
Exercise 4 - Finally
Add .finally() to your fetch call from Exercise 3. It should log "Request finished" whether the fetch succeeded or failed.
Run it twice - once with a working URL, once with a broken one. Confirm "Request finished" appears both times.
Exercise 5 - Fetching a List
Fetch all users from https://jsonplaceholder.typicode.com/users. When the data arrives:
- Log how many users there are
- Loop through them and log each user's
nameandemail - Include
.catch()and.finally()
Write the whole thing from scratch using arrow functions throughout.