Lesson 8 of 8

Caching requests

Goal

One request per ID

01

Explanation

If five components on a page ask for the same user's data, five identical requests go to the server. A simple cache turns them into one: a Map that links each ID to its request.

The trap is in what you store. If you store the result after await, every call that comes in at the same moment finds the cache empty, so they all send their requests at once. Instead, store the promise itself the moment you send the request, and every caller after that shares that same request, even while it's still in flight.

Storing the promise has a price, because a rejected promise stays rejected. If the request fails, remove it from the cache, or the user stays stuck on the error until they reload the page.

02

Your task

Make getUser(id) fetch each ID from the network only once, even when it's called for that ID several times at the same moment, and remove the ID from the cache if its request fails.

Checks

5 checks
  1. getUser returns the requested user
  2. A repeated call gets its result from the cache
  3. Calls made at the same moment share one request
  4. Each ID gets its own request and result
  5. A failed request doesn't stay in the cache
03

Hints

0/3
Track lessons0 of 8 done

Learn to read JSON, wait for the server to respond, and handle loading and failure states. That's what separates a demo from a product people can rely on.

Intermediate level, 8 lessons, 2 hours in total.

index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.

Track lessons0 of 8 done

Learn to read JSON, wait for the server to respond, and handle loading and failure states. That's what separates a demo from a product people can rely on.

Intermediate level, 8 lessons, 2 hours in total.