0
0
Node.jsframework~5 mins

AbortController for cancellation in Node.js

Choose your learning style9 modes available
Introduction

AbortController helps you stop a task that is running, like a network request, when you no longer need it. This saves time and resources.

You want to cancel a fetch request if the user navigates away from the page.
You want to stop a long-running operation if it takes too long.
You want to clean up resources when a task is no longer needed.
You want to handle user actions like cancel buttons that stop ongoing tasks.
Syntax
Node.js
const controller = new AbortController();
const signal = controller.signal;

// Pass signal to an async operation like fetch
fetch(url, { signal })
  .then(response => { /* handle response */ })
  .catch(error => {
    if (error.name === 'AbortError') {
      // Handle cancellation
    }
  });

// To cancel the operation
controller.abort();

The signal is passed to the async operation to listen for cancellation.

Calling controller.abort() triggers the cancellation.

Examples
This example fetches data but cancels the request if it takes longer than 2 seconds.
Node.js
const controller = new AbortController();
const signal = controller.signal;

fetch('https://example.com/data', { signal })
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Fetch aborted');
    } else {
      console.error('Fetch error:', err);
    }
  });

// Cancel after 2 seconds
setTimeout(() => controller.abort(), 2000);
This async function loads data and handles cancellation gracefully.
Node.js
const controller = new AbortController();
const signal = controller.signal;

async function loadData() {
  try {
    const response = await fetch('https://example.com/api', { signal });
    const data = await response.json();
    console.log('Data loaded:', data);
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Loading cancelled');
    } else {
      console.error('Error:', error);
    }
  }
}

loadData();

// Cancel after 1 second
setTimeout(() => controller.abort(), 1000);
Sample Program

This program starts a fetch request to get a todo item. It cancels the fetch after 500 milliseconds. You will see the abort message if the fetch is stopped before completion.

Node.js
import fetch from 'node-fetch';

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

async function fetchWithCancel() {
  try {
    console.log('Starting fetch...');
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1', { signal });
    const data = await response.json();
    console.log('Fetch completed:', data);
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('Fetch was aborted');
    } else {
      console.error('Fetch error:', error);
    }
  }
}

fetchWithCancel();

// Abort the fetch after 500ms
setTimeout(() => {
  console.log('Aborting fetch...');
  controller.abort();
}, 500);
OutputSuccess
Important Notes

Always check for error.name === 'AbortError' to detect cancellation.

AbortController works well with fetch and other APIs that support signals.

Canceling tasks helps improve app performance and user experience.

Summary

AbortController lets you stop async tasks like fetch requests.

Pass the controller's signal to the task and call abort() to cancel.

Handle the abort error to respond properly when a task is cancelled.