Exercises
Objectives
This chapter introduces no new concepts. It’s a chance to practice everything from this module: timers, callbacks, promises, async/await, fetch, and error handling.
Exercises 1-8 use this starting code:
function delayedValue(value, ms) {
return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
function delayedFailure(ms) {
return new Promise((_, reject) => setTimeout(() => reject(new Error("failed")), ms));
}
Exercises
-
Use
setTimeout()to log"Hello"after 200ms. Check: it logs, but only after the delay, not immediately. -
Use
setInterval()to log"tick"and count how many times it’s run, stopping itself withclearInterval()once the count reaches3. Check: exactly three ticks log. -
Write a function
double(n, callback)that callscallback(n * 2). Call it with4and a callback that logs the result. Check:8. -
Call
delayedValue("done", 300)and use.then()to log the result. Check:done. -
Call
delayedFailure(200)and use.catch()to log the error’s.message. Check:failed. -
Write an
asyncfunction that awaitsdelayedValue("ok", 100)and returns it. Check: calling it and awaiting the result givesok. -
Write an
asyncfunction that awaitsdelayedFailure(100)inside atry/catch, returning the caught error’s.messagefrom thecatchblock. Check:failed. -
Use
Promise.all()withdelayedValue("A", 100)anddelayedValue("B", 50), and log the result. Check:["A", "B"], in that order, even though"B"resolves first.
Exercises 9-12 use the same practice API from lessons 5 and 6, JSONPlaceholder. It has 10 users, ids 1 through 10.
-
Write an
asyncfunction that fetches"https://jsonplaceholder.typicode.com/users/1", checksresponse.status, and logsdata.namefrom the parsed JSON body. Check: status is200, name isLeanne Graham. -
Write an
asyncfunction that fetches"https://jsonplaceholder.typicode.com/users/9999"and logsresponse.okandresponse.status, without calling.json()or throwing. Check:okisfalse,statusis404. Confirm for yourself that no error was thrown,fetch()resolved normally. -
Write an
asyncfunctiongetUser(id)that fetches`https://jsonplaceholder.typicode.com/users/${id}`, throws an error including the status ifresponse.okisfalse, and otherwise returns the parsed JSON. Call it with9999inside atry/catchand log the caught message. Check: the message includes404. -
Write an
asyncfunction that sends aPOSTrequest to"https://jsonplaceholder.typicode.com/posts"with a JSON body of{ title: "Hello", body: "My first post", userId: 1 }, including theContent-Type: application/jsonheader, and logs the parsed response. Check: the response includes the fields you sent, plus a newid.
Recap
You can now delay and repeat code with timers, pass and receive results through callbacks, work with promises directly or through async/await, request and send data with fetch(), and handle both network failures and bad HTTP statuses. That’s the complete toolkit for code that doesn’t finish immediately.
Next module: Modules and Code Organization, splitting a growing project across multiple files.