Μετάβαση στο κύριο περιεχόμενο
← ⚡ JavaScript & the browser·Ενότητα C9 · Μάθημα 7
ΕργασίαImplement 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
Θεωρία

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.

🔒

Εγγράψου για να αρχίσεις να προγραμματίζεις

Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.

Εγγραφή — δωρεάν δοκιμή →

Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.

← ΠροηγούμενοΕπόμενο μάθημα →

Μια συμβουλή Python ή web την ημέρα — με email

Σύντομο, γραμμένο στο χέρι, χωρίς spam. Διαγραφή με ένα κλικ.