AbortController With Fetch
NodeJS
Hard
4 views
Problem Description
Cancel a fetch request using AbortController and print ABORTED.
Output Format
Print ABORTED or OK.
Constraints
Use a fake fetch with timeout for demo.
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!
No comments yet. Start the discussion!