0
0
DenoHow-ToBeginner ยท 4 min read

How to Use AbortController in Deno for Request Cancellation

In Deno, you use AbortController to cancel asynchronous tasks like fetch requests by creating an instance, passing its signal to the task, and calling abort() to stop it. This helps manage long-running or unwanted operations cleanly.
๐Ÿ“

Syntax

The AbortController API in Deno works by creating a controller object that provides a signal. This signal is passed to asynchronous functions like fetch to allow cancellation. Calling abort() on the controller triggers the cancellation.

  • AbortController(): Creates a new controller instance.
  • controller.signal: The signal to pass to async functions.
  • controller.abort(): Cancels the operation linked to the signal.
typescript
const controller = new AbortController();
const signal = controller.signal;

// Pass signal to async operation
fetch('https://example.com', { signal })
  .then(response => console.log('Success'))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Fetch aborted');
    } else {
      console.error('Fetch error:', err);
    }
  });

// To cancel:
controller.abort();
๐Ÿ’ป

Example

This example shows how to start a fetch request and cancel it after 1 second using AbortController. The fetch will throw an AbortError which we catch and handle gracefully.

typescript
const controller = new AbortController();
const signal = controller.signal;

const fetchPromise = fetch('https://httpbin.org/delay/5', { signal })
  .then(response => response.text())
  .then(text => console.log('Fetch completed:', text))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Fetch was aborted');
    } else {
      console.error('Fetch failed:', err);
    }
  });

// Abort fetch after 1 second
setTimeout(() => {
  controller.abort();
}, 1000);
Output
Fetch was aborted
โš ๏ธ

Common Pitfalls

Common mistakes when using AbortController in Deno include:

  • Not passing the signal to the async function, so abort has no effect.
  • Not handling the AbortError in the catch block, causing unhandled exceptions.
  • Calling abort() too late or too early, missing the cancellation window.

Always ensure the signal is passed and errors are caught properly.

typescript
/* Wrong: Missing signal, abort does nothing */
const controller = new AbortController();
fetch('https://httpbin.org/delay/5')
  .catch(err => console.error(err));
controller.abort();

/* Right: Pass signal and handle abort error */
const controller2 = new AbortController();
fetch('https://httpbin.org/delay/5', { signal: controller2.signal })
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Fetch aborted correctly');
    }
  });
controller2.abort();
Output
Fetch aborted correctly
๐Ÿ“Š

Quick Reference

Summary tips for using AbortController in Deno:

  • Create an AbortController instance before starting the async task.
  • Pass controller.signal to the async function options.
  • Call controller.abort() to cancel the task.
  • Catch AbortError to handle cancellation gracefully.
  • Use abort to improve app responsiveness and resource management.
โœ…

Key Takeaways

Use AbortController to cancel async operations like fetch by passing its signal.
Always handle AbortError in catch blocks to avoid uncaught exceptions.
Call abort() on the controller to stop the operation cleanly.
Passing the signal is required; without it, abort has no effect.
AbortController helps manage resources and improve app responsiveness.