CodingNic

Asynchronous JavaScript

Exercises

Asynchronous JavaScript 40 min read

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:

javascript
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

  1. Use setTimeout() to log "Hello" after 200ms. Check: it logs, but only after the delay, not immediately.

  2. Use setInterval() to log "tick" and count how many times it’s run, stopping itself with clearInterval() once the count reaches 3. Check: exactly three ticks log.

  3. Write a function double(n, callback) that calls callback(n * 2). Call it with 4 and a callback that logs the result. Check: 8.

  4. Call delayedValue("done", 300) and use .then() to log the result. Check: done.

  5. Call delayedFailure(200) and use .catch() to log the error’s .message. Check: failed.

  6. Write an async function that awaits delayedValue("ok", 100) and returns it. Check: calling it and awaiting the result gives ok.

  7. Write an async function that awaits delayedFailure(100) inside a try/catch, returning the caught error’s .message from the catch block. Check: failed.

  8. Use Promise.all() with delayedValue("A", 100) and delayedValue("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.

  1. Write an async function that fetches "https://jsonplaceholder.typicode.com/users/1", checks response.status, and logs data.name from the parsed JSON body. Check: status is 200, name is Leanne Graham.

  2. Write an async function that fetches "https://jsonplaceholder.typicode.com/users/9999" and logs response.ok and response.status, without calling .json() or throwing. Check: ok is false, status is 404. Confirm for yourself that no error was thrown, fetch() resolved normally.

  3. Write an async function getUser(id) that fetches `https://jsonplaceholder.typicode.com/users/${id}`, throws an error including the status if response.ok is false, and otherwise returns the parsed JSON. Call it with 9999 inside a try/catch and log the caught message. Check: the message includes 404.

  4. Write an async function that sends a POST request to "https://jsonplaceholder.typicode.com/posts" with a JSON body of { title: "Hello", body: "My first post", userId: 1 }, including the Content-Type: application/json header, and logs the parsed response. Check: the response includes the fields you sent, plus a new id.

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.