Request cancellation with AbortController

The Aurelia Fetch Client fully supports the native AbortController API for cancelling HTTP requests. Understanding how to properly use AbortController is crucial for building responsive applications and managing resource cleanup.

Basic Request Cancellation

Simple Abort Example

import { IHttpClient } from '@aurelia/fetch-client';
import { resolve } from '@aurelia/kernel';

export class CancellableRequestService {
  private http = resolve(IHttpClient);

  async fetchDataWithCancellation(): Promise<{ data: any; abort: () => void }> {
    const controller = new AbortController();
    
    const dataPromise = this.http.get('/api/large-dataset', {
      signal: controller.signal
    }).then(response => {
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      return response.json();
    });

    return {
      data: dataPromise,
      abort: () => controller.abort()
    };
  }

  // Usage example
  async loadDataWithTimeout() {
    const { data, abort } = await this.fetchDataWithCancellation();
    
    // Auto-cancel after 10 seconds
    const timeoutId = setTimeout(() => {
      abort();
      console.log('Request cancelled due to timeout');
    }, 10000);

    try {
      const result = await data;
      clearTimeout(timeoutId);
      return result;
    } catch (error) {
      clearTimeout(timeoutId);
      if (error.name === 'AbortError') {
        console.log('Request was cancelled');
        return null;
      }
      throw error;
    }
  }
}

Component Integration

AbortController with Interceptors

Interceptor Handling

Interceptors properly handle aborted requests through the error chain:

Critical Issue: AbortController + Retry Bug

⚠️ Important Limitation: There is a critical bug in the current retry mechanism when used with AbortController. When a request with an AbortSignal is retried, the retry attempts inherit the same (potentially aborted) signal, causing all retry attempts to immediately fail.

The Problem

Workaround Solutions

Solution 2: Manual Retry with Fresh AbortController

Advanced Cancellation Patterns

Timeout with Custom Error Messages

Race Conditions and Multiple Requests

File Upload Cancellation

Best Practices

Error Handling

Always check for AbortError specifically:

Resource Cleanup

Always clean up AbortControllers when components are destroyed:

Avoid Common Pitfalls

  1. Don't reuse AbortControllers: Create a new one for each request

  2. Handle AbortError gracefully: It's usually not an actual error condition

  3. Clean up timeouts: Always clear timeout IDs when requests complete

  4. Be aware of the retry bug: Use workarounds when combining AbortController with retries

Integration with Aurelia Lifecycle

Understanding these patterns and limitations will help you build robust, cancellable HTTP operations in your Aurelia applications while avoiding the current retry mechanism bug.

Last updated

Was this helpful?