Bird
Raised Fist0
Node.jsframework~10 mins

AbortController for cancellation in Node.js - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - AbortController for cancellation
Create AbortController
Start async task with signal
Task running...
AbortController.abort() called?
NoTask completes normally
Task receives abort signal
Task cancels early
Handle task result or cancellation
This flow shows how an AbortController creates a signal to cancel an async task early if needed.
Execution Sample
Node.js
const controller = new AbortController();
const signal = controller.signal;

fetch('https://example.com', { signal })
  .then(() => console.log('Success'))
  .catch(e => console.log('Aborted:', e.name));

controller.abort();
Starts a fetch request with an abort signal, then cancels it immediately.
Execution Table
StepActionSignal StateTask StateOutput
1Create AbortControllernot abortednot started
2Start fetch with signalnot abortedrunning
3AbortController.abort() calledabortedrunning
4Fetch detects abort signalabortedcancelled
5Fetch promise rejectsabortedcancelledAborted: AbortError
6Catch block runsabortedcancelledAborted: AbortError
💡 Fetch is cancelled because abort() was called, causing the promise to reject with AbortError.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
controller.signal.abortedfalsefalsetruetrue
fetch task statenot startedrunningrunningcancelled
Key Moments - 3 Insights
Why does the fetch promise reject after calling controller.abort()?
Because the abort signal changes to aborted (see Step 3 in execution_table), the fetch detects this and rejects with an AbortError (Step 5).
Does calling abort() immediately stop the fetch function?
No, abort() signals cancellation but the fetch promise rejects asynchronously after detecting the signal (Steps 3 to 5).
What happens if abort() is never called?
The fetch runs normally and resolves or rejects based on network response, without cancellation (Step 2 runs to completion).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the signal.aborted value after Step 3?
Aundefined
Bfalse
Ctrue
Dnull
💡 Hint
Check the 'Signal State' column at Step 3 in the execution_table.
At which step does the fetch task change from running to cancelled?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look at the 'Task State' column in the execution_table to see when it changes.
If controller.abort() was not called, what would happen to the fetch task state?
AIt would stay running forever
BIt would complete normally
CIt would cancel automatically
DIt would throw an error immediately
💡 Hint
Refer to the key_moments explanation about what happens if abort() is never called.
Concept Snapshot
AbortController creates a signal to cancel async tasks.
Pass signal to async function (like fetch).
Call abort() to set signal.aborted = true.
Async task detects signal and cancels early.
Promise rejects with AbortError on cancellation.
Full Transcript
AbortController is a tool in Node.js to cancel asynchronous operations early. You create an AbortController instance, then get its signal property. This signal is passed to async functions like fetch. When you call abort() on the controller, the signal's aborted property becomes true. The async function notices this and stops its work, rejecting its promise with an AbortError. This lets you handle cancellations cleanly. The execution flow starts with creating the controller, then starting the async task with the signal. If abort() is called, the task detects the signal and cancels. Otherwise, it runs to completion. Variables like signal.aborted and the task state change step-by-step as shown in the execution table. Understanding when and how abort() affects the task helps avoid confusion about asynchronous cancellation.

Practice

(1/5)
1. What is the main purpose of AbortController in Node.js?
easy
A. To manage file system permissions
B. To create new HTTP servers
C. To cancel ongoing asynchronous operations like fetch requests
D. To handle database connections

Solution

  1. Step 1: Understand AbortController's role

    AbortController is designed to stop or cancel asynchronous tasks such as fetch requests.
  2. Step 2: Compare with other options

    Creating servers, managing permissions, or handling databases are unrelated to AbortController's purpose.
  3. Final Answer:

    To cancel ongoing asynchronous operations like fetch requests -> Option C
  4. Quick Check:

    AbortController cancels async tasks = C [OK]
Hint: AbortController is about stopping async tasks quickly [OK]
Common Mistakes:
  • Confusing AbortController with server or database management
  • Thinking it manages permissions
  • Assuming it creates servers
2. Which of the following is the correct way to create an AbortController and get its signal?
easy
A. const signal = new AbortController.signal();
B. const controller = new AbortController; const signal = controller.abort();
C. const controller = AbortController(); const signal = controller.abort;
D. const controller = new AbortController(); const signal = controller.signal;

Solution

  1. Step 1: Check correct instantiation syntax

    AbortController must be created with 'new AbortController()' and its signal accessed via 'controller.signal'.
  2. Step 2: Identify errors in other options

    const signal = new AbortController.signal(); wrongly calls signal as a constructor. const controller = AbortController(); const signal = controller.abort; misses 'new' and uses 'abort' instead of 'signal'. const controller = new AbortController; const signal = controller.abort(); misses parentheses on 'new AbortController()' and calls 'abort()' instead of accessing 'signal'.
  3. Final Answer:

    const controller = new AbortController(); const signal = controller.signal; -> Option D
  4. Quick Check:

    Use 'new' and access 'signal' property = B [OK]
Hint: Always use 'new AbortController()' and get 'signal' property [OK]
Common Mistakes:
  • Forgetting 'new' keyword
  • Calling 'abort' instead of accessing 'signal'
  • Treating 'signal' as a constructor
3. What will be the output of this code snippet?
const controller = new AbortController();
const signal = controller.signal;

setTimeout(() => controller.abort(), 100);

signal.addEventListener('abort', () => console.log('Aborted!'));
medium
A. Logs 'Aborted!' after 100 milliseconds
B. Logs 'Aborted!' immediately
C. Throws an error immediately
D. No output, because abort is never called

Solution

  1. Step 1: Understand the abort timing

    The controller.abort() is called after 100 milliseconds using setTimeout.
  2. Step 2: Check event listener behavior

    The signal listens for 'abort' event and logs 'Aborted!' when triggered.
  3. Final Answer:

    Logs 'Aborted!' after 100 milliseconds -> Option A
  4. Quick Check:

    Abort triggers event after delay = D [OK]
Hint: Abort triggers event after delay, not immediately [OK]
Common Mistakes:
  • Assuming abort happens immediately
  • Expecting no output because of async delay
  • Thinking it throws error instead of event
4. Identify the error in this code snippet that uses AbortController:
const controller = new AbortController();
const signal = controller.signal;

fetch('https://example.com', { signal });
controller.abort();

signal.addEventListener('abort', () => console.log('Fetch aborted'));
medium
A. Not passing the signal to fetch options
B. Calling abort() before adding the abort event listener
C. Using signal.addEventListener instead of controller.addEventListener
D. Missing async/await for fetch

Solution

  1. Step 1: Check event listener timing

    The abort event listener is added after calling controller.abort(), so it misses the event.
  2. Step 2: Verify other parts

    The signal is correctly passed to fetch, and signal is the right object to listen on. Async/await is optional here.
  3. Final Answer:

    Calling abort() before adding the abort event listener -> Option B
  4. Quick Check:

    Add event listener before abort() call = A [OK]
Hint: Add abort listener before calling abort() [OK]
Common Mistakes:
  • Adding listener after abort() call
  • Listening on controller instead of signal
  • Forgetting to pass signal to fetch
5. You want to cancel a fetch request if it takes longer than 200ms. Which code correctly implements this using AbortController?
hard
A. const controller = new AbortController(); setTimeout(() => controller.abort(), 200); fetch('https://api.com/data', { signal: controller.signal }) .catch(err => { if (err.name === 'AbortError') console.log('Request timed out'); });
B. const controller = new AbortController(); fetch('https://api.com/data', { signal: controller.signal }); setTimeout(() => controller.abort(), 200); console.log('Request timed out');
C. const controller = new AbortController(); fetch('https://api.com/data'); setTimeout(() => controller.abort(), 200); .catch(err => console.log('Request timed out'));
D. const controller = new AbortController(); setTimeout(() => controller.abort(), 200); fetch('https://api.com/data', { signal: controller.abort() }) .catch(err => console.log('Request timed out'));

Solution

  1. Step 1: Setup AbortController and timeout

    Create controller, set timeout to call abort after 200ms.
  2. Step 2: Pass signal to fetch and handle abort error

    Pass controller.signal to fetch options and catch AbortError to log timeout message.
  3. Step 3: Identify errors in other options

    const controller = new AbortController(); fetch('https://api.com/data', { signal: controller.signal }); setTimeout(() => controller.abort(), 200); console.log('Request timed out'); logs timeout immediately, not on abort. const controller = new AbortController(); fetch('https://api.com/data'); setTimeout(() => controller.abort(), 200); .catch(err => console.log('Request timed out')); misses passing signal. const controller = new AbortController(); setTimeout(() => controller.abort(), 200); fetch('https://api.com/data', { signal: controller.abort() }) .catch(err => console.log('Request timed out')); incorrectly calls abort() instead of passing signal.
  4. Final Answer:

    const controller = new AbortController(); setTimeout(() => controller.abort(), 200); fetch('https://api.com/data', { signal: controller.signal }) .catch(err => { if (err.name === 'AbortError') console.log('Request timed out'); }); -> Option A
  5. Quick Check:

    Pass signal, abort after delay, catch AbortError = A [OK]
Hint: Pass controller.signal to fetch and abort after timeout [OK]
Common Mistakes:
  • Calling abort() instead of passing signal
  • Logging timeout before abort happens
  • Not passing signal to fetch