NodeJS Program to AbortController With Fetch with Explanation
NodeJS
Hard
Async & Event Loop
35 views
1 min read
83 words
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around fetch, abortcontroller, aborted. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Cancel a fetch request using AbortController and print ABORTED.
Input Format
No input.
Output Format
Print ABORTED or OK.
Constraints
Use a fake fetch with timeout for demo.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
function fakeFetch(signal) {
return new Promise((resolve, reject) => {
const id = setTimeout(() => resolve('OK'), 200);
signal.addEventListener('abort', () => {
clearTimeout(id);
reject(new Error('aborted'));
});
});
}
(async () => {
const ac = new AbortController();
setTimeout(() => ac.abort(), 20);
try {
await fakeFetch(ac.signal);
console.log('OK');
} catch (e) {
console.log('ABORTED');
}
})();
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Cancel a fetch request using AbortController and print ABORTED.
Input / Output
Output
Print ABORTED or OK.
Constraints
Use a fake fetch with timeout for demo.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
function fakeFetch(signal) {
return new Promise((resolve, reject) => {
const id = setTimeout(() => resolve('OK'), 200);
signal.addEventListener('abort', () => {
clearTimeout(id);
reject(new Error('aborted'));
});
});
}
(async () => {
const ac = new AbortController();
setTimeout(() => ac.abort(), 20);
try {
await fakeFetch(ac.signal);
console.log('OK');
} catch (e) {
console.log('ABORTED');
}
})();
Solutions (0)
No solutions submitted yet. Be the first!