Bird
0
0

How would you implement a fetch request in Node.js that automatically cancels if it does not complete within 2 seconds using AbortController?

hard📝 Application Q8 of 15
Node.js - Timers and Scheduling
How would you implement a fetch request in Node.js that automatically cancels if it does not complete within 2 seconds using AbortController?
A<pre>const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 2000); fetch(url, { signal: controller.signal }) .finally(() => clearTimeout(timeout));</pre>
B<pre>const controller = AbortController(); setTimeout(controller.abort, 2000); fetch(url, { signal: controller.signal });</pre>
C<pre>const controller = new AbortController(); fetch(url, { signal: controller.signal }); setTimeout(() => controller.abort(), 2000);</pre>
D<pre>const controller = new AbortController(); fetch(url); setTimeout(() => controller.abort(), 2000);</pre>
Step-by-Step Solution
Solution:
  1. Step 1: Create AbortController instance

    Use new AbortController() to create the controller.
  2. Step 2: Setup timeout to abort

    Use setTimeout to call controller.abort() after 2000ms.
  3. Step 3: Pass signal to fetch

    Include signal: controller.signal in fetch options to enable cancellation.
  4. Step 4: Clear timeout after fetch completes

    Use finally to clear the timeout to avoid unnecessary aborts.
  5. Final Answer:

    Option A -> Option A
  6. Quick Check:

    Check for 'new', passing signal, and clearing timeout [OK]
Quick Trick: Always clear timeout after fetch to prevent unwanted aborts [OK]
Common Mistakes:
  • Not using 'new' when creating AbortController
  • Not passing signal to fetch
  • Not clearing timeout after fetch completes
  • Calling abort without binding or parentheses

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes