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
Using AbortController for Cancellation in Node.js
📖 Scenario: You are building a Node.js script that fetches data from a slow API. Sometimes, the user wants to cancel the request if it takes too long.To handle this, you will use AbortController to cancel the fetch request after a timeout.
🎯 Goal: Create a Node.js script that fetches data from https://jsonplaceholder.typicode.com/todos/1 and cancels the request if it takes more than 2 seconds.
📋 What You'll Learn
Create an AbortController instance
Set a timeout to abort the fetch after 2 seconds
Use the signal from the controller in the fetch request
Handle the abort error gracefully
💡 Why This Matters
🌍 Real World
AbortController is useful in real apps to stop slow or unwanted network requests, improving user experience and saving resources.
💼 Career
Understanding AbortController is important for Node.js developers working with APIs, especially when building responsive and efficient applications.
Progress0 / 4 steps
1
Create an AbortController instance
Create a variable called controller and assign it a new AbortController() instance.
Node.js
Hint
Use new AbortController() to create the controller.
2
Set a timeout to abort the controller
Create a timeout using setTimeout that calls controller.abort() after 2000 milliseconds.
Node.js
Hint
Use setTimeout with 2000 ms and call controller.abort() inside.
3
Fetch data with the abort signal
Write a fetch call to https://jsonplaceholder.typicode.com/todos/1 using await inside an async function called fetchData. Pass signal: controller.signal as an option to fetch.
Node.js
Hint
Use fetch with the signal option from the controller.
4
Handle abort error and call fetchData
Call fetchData() and catch errors. If the error's name is 'AbortError', log 'Fetch aborted'. Otherwise, rethrow the error.
Node.js
Hint
Use .catch on the promise returned by fetchData() to handle abort errors.
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
Step 1: Understand AbortController's role
AbortController is designed to stop or cancel asynchronous tasks such as fetch requests.
Step 2: Compare with other options
Creating servers, managing permissions, or handling databases are unrelated to AbortController's purpose.
Final Answer:
To cancel ongoing asynchronous operations like fetch requests -> Option C
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
Step 1: Check correct instantiation syntax
AbortController must be created with 'new AbortController()' and its signal accessed via 'controller.signal'.
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'.
Final Answer:
const controller = new AbortController(); const signal = controller.signal; -> Option D
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
Step 1: Understand the abort timing
The controller.abort() is called after 100 milliseconds using setTimeout.
Step 2: Check event listener behavior
The signal listens for 'abort' event and logs 'Aborted!' when triggered.
Final Answer:
Logs 'Aborted!' after 100 milliseconds -> Option A
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
Step 1: Check event listener timing
The abort event listener is added after calling controller.abort(), so it misses the event.
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.
Final Answer:
Calling abort() before adding the abort event listener -> Option B
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
Step 1: Setup AbortController and timeout
Create controller, set timeout to call abort after 200ms.
Step 2: Pass signal to fetch and handle abort error
Pass controller.signal to fetch options and catch AbortError to log timeout message.