1. Use fetch API and AbortController
Modern browser supportfetch
API, and provides aAbortController
The interface to abort the request.
const controller = new AbortController(); const signal = ; fetch('/some/api/endpoint', { signal }) .then(response => { if () { return (); } else { throw new Error('Network response was not ok'); } }) .catch(error => { if ( === 'AbortError') { ('Fetch aborted'); } else { ('Fetch error:', error); } }); // Call when a request is aborted();
In this example, AbortController creates a signal object signal, which is passed to the options object of the fetch request. When () is called, the request will be aborted, and the fetch's Promise will be rejected, throwing an AbortError.
2. Use XMLHttpRequest and abort methods
For older code or scenarios that require finer granular control, XMLHttpRequest may be being used.
const xhr = new XMLHttpRequest(); ('GET', '/some/api/endpoint', true); = function () { if ( === 4) { if ( === 200) { (); } else { ('Request failed:', ); } } }; (); // Call when a request is aborted();
In this example,()
The method will abort the request immediately. If the request has been completed (i.e.readyState
Already 4), then callabort()
There will be no effect.
3. Use third-party libraries (such as Axios)
If you are using a third-party HTTP client library like Axios, it usually provides the ability to abort requests as well.
const CancelToken = ; const source = (); ('/some/api/endpoint', { cancelToken: }).catch(function (thrown) { if ((thrown)) { ('Request canceled', ); } else { // Handle errors } }); // Call when a request is aborted('Operation canceled by the user.');
In this example, CancelToken is used to create a token that can cancel the request. When () is called, the request is aborted, and the Promise is rejected, throwing an error containing the cancel information.
Summarize
The ability to abort network requests is very important to improve the performance and user experience of web applications. Modern browsers and HTTP client libraries usually provide corresponding APIs to implement this functionality.