Request cancellation with AbortController
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
Critical Issue: AbortController + Retry Bug
The Problem
Workaround Solutions
Solution 1: Conditional Retry (Recommended)
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
Resource Cleanup
Avoid Common Pitfalls
Integration with Aurelia Lifecycle
Last updated
Was this helpful?