Přejít k hlavnímu obsahu
← ⚡ JavaScript & the browser·Modul C9 · Lekce 7
ÚkolImplement wait(ms, signal) returning a Promise. setTimeout resolves; signal.abort triggers reject with AbortError. Create ctrl, schedule ctrl.abort() in 30ms, try await wait(200, ctrl.signal) in try/catch, log err.name.

AbortController as a cancellation token

125 XP9 min
Teorie

Not just for fetch

C4 used AbortController to cancel a fetch. The same API is a generic cancellation token — any function that accepts a signal can be cancelled.

function wait(ms, signal) {
  return new Promise((resolve, reject) => {
    const id = setTimeout(resolve, ms);
    signal?.addEventListener("abort", () => {
      clearTimeout(id);
      reject(new DOMException("aborted", "AbortError"));
    });
  });
}

const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), 50);

try {
  await wait(500, ctrl.signal);
} catch (err) {
  console.log(err.name); // "AbortError"
}

The contract

  • Accept signal as an option.
  • If signal is already aborted on entry, reject immediately.
  • Subscribe to abort and reject + clean up resources.
  • Throw an AbortError (DOMException with name "AbortError").

Why a standard

Any library that adopts this can be cancelled with the same controller as your fetch. One controller can abort multiple operations at once — pass the same signal to fetch, wait, db query, anything.

🔒

Zaregistruj se a začni programovat

Teorie je otevřená pro každého. Editor, živý náhled a check se odemknou s 7denní zkušební verzí zdarma — karta vyžadována, zrušíš kdykoli.

Registrace — zkušební verze zdarma →

Prvních 10 lekcí v každé trase je zdarma. Karta není potřeba.

← PředchozíDalší lekce →

Jeden tip k Pythonu nebo webu denně — e-mailem

Krátké, ručně psané, žádný spam. Odhlásit jedním klikem.