AJAX & Async Requests·AJAX from first request to live updates

Caching and cancellation

Avoid duplicate requests with caching and cancel stale ones.

Beginner 13 min read Lesson 9 of 300 Challenge included
What you will be able to do
  • Use Cache-Control on the server.
  • Use AbortController for stale requests.
  • Cache GET responses in memory briefly.
  • Never cache private user data in a shared layer.

In plain English

A cached response saves time and bandwidth. AbortController cancels outdated requests, which is essential for type-ahead search. Combine a short client cache with correct server headers.

abort.jsJavaScript
let controller
async function search(term) {
  controller?.abort()
  controller = new AbortController()
  try {
    const response = await fetch('/api/search?q=' + encodeURIComponent(term), { signal: controller.signal })
    return await response.json()
  } catch (error) {
    if (error.name !== 'AbortError') throw error
  }
}
Your turn

Cancel the previous request

Medium

Abort the previous controller before starting a new search.

JAVASCRIPT · starter
controller = new AbortController()
Check your understanding before moving on.
Knowledge checkQuestion 1

Which error name indicates an intentional abort?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Build live search
Lesson 9 of 300 · 0% of course