Many developers might think they understand AbortController, but its capabilities go far beyond the basics. From canceling fetch requests to managing event listeners and React hooks.
Do you really know how powerful AbortController is? Let's see:
Using AbortController with fetch, of course, is the most common usage.
Here’s an example demonstrating how AbortController can be used to create cancelable fetch requests:
fetchButton.onclick = async () => { const controller = new AbortController(); // Add a cancel button abortButton.onclick = () => controller.abort(); try { const response = await fetch('/json', { signal: controller.signal }); const data = await response.json(); // Perform business logic here } catch (error) { const isUserAbort = error.name === 'AbortError'; // AbortError is thrown when the request is canceled using AbortController } };
The above example showcases something that was impossible before the introduction of AbortController: the ability to cancel network requests programmatically. When canceled, the browser halts the fetch, saving network bandwidth. Importantly, the cancellation doesn’t have to be user-initiated.
The controller.signal provides an AbortSignal object, enabling communication with asynchronous operations like fetch and allowing them to be canceled.
For combining multiple signals into a single signal, you can use AbortSignal.any(). Here’s how:
try { const controller = new AbortController(); const timeoutSignal = AbortSignal.timeout(5000); const response = await fetch(url, { // Abort fetch if any of the signals are triggered signal: AbortSignal.any([controller.signal, timeoutSignal]), }); const data = await response.json(); } catch (error) { if (error.name === 'AbortError') { // Notify the user of cancellation } else if (error.name === 'TimeoutError') { // Notify the user of timeout } else { // Handle other errors, like network issues console.error(`Type: ${error.name}, Message: ${error.message}`); } }
For AbortSignal, You can:
if (signal.aborted) { } signal.addEventListener('abort', () => {});
When a request is canceled using AbortController, the server won’t process it or send a response, saving bandwidth and improving client-side performance by reducing concurrent connections.
Older APIs like WebSocket don’t natively support AbortSignal. Instead, you can implement cancellation like this:
function abortableSocket(url, signal) { const socket = new WebSocket(url); if (signal.aborted) { socket.close(); // Abort immediately if already canceled } signal.addEventListener('abort', () => socket.close()); return socket; }
Note: If AbortSignal is already aborted, it won’t trigger the abort event, so you need to check and handle this case upfront.
Traditionally, removing event listeners requires passing the exact same function reference:
window.addEventListener('resize', () => doSomething()); window.removeEventListener('resize', () => doSomething()); // This won’t work
With AbortController, this becomes easier:
const controller = new AbortController(); const { signal } = controller; window.addEventListener('resize', () => doSomething(), { signal }); // Remove the event listener by calling abort() controller.abort();
For older browsers, consider adding a polyfill to support AbortController.
In React, effects can inadvertently run in parallel if the component updates before a previous asynchronous task completes:
function FooComponent({ something }) { useEffect(async () => { const data = await fetch(url + something); // Handle the data }, [something]); return ...>; }
To avoid such issues, use AbortController to cancel previous tasks:
fetchButton.onclick = async () => { const controller = new AbortController(); // Add a cancel button abortButton.onclick = () => controller.abort(); try { const response = await fetch('/json', { signal: controller.signal }); const data = await response.json(); // Perform business logic here } catch (error) { const isUserAbort = error.name === 'AbortError'; // AbortError is thrown when the request is canceled using AbortController } };
Modern Node.js includes a setTimeout implementation compatible with AbortController:
try { const controller = new AbortController(); const timeoutSignal = AbortSignal.timeout(5000); const response = await fetch(url, { // Abort fetch if any of the signals are triggered signal: AbortSignal.any([controller.signal, timeoutSignal]), }); const data = await response.json(); } catch (error) { if (error.name === 'AbortError') { // Notify the user of cancellation } else if (error.name === 'TimeoutError') { // Notify the user of timeout } else { // Handle other errors, like network issues console.error(`Type: ${error.name}, Message: ${error.message}`); } }
Unlike browser setTimeout, this implementation doesn’t accept a callback; instead, use .then() or await.
Browsers are moving toward scheduler.postTask() for task prioritization, with TaskController extending AbortController. You can use it to cancel tasks and dynamically adjust their priority:
if (signal.aborted) { } signal.addEventListener('abort', () => {});
If priority control isn’t needed, you can simply use AbortController instead.
AbortController is an essential tool in modern JavaScript development, offering a standardized way to manage and cancel asynchronous tasks.
Its integration into both browser and Node.js environments highlights its versatility and importance.
If you don't know AbortController, now it’s time to embrace its full capabilities and make it a cornerstone of your asynchronous programming toolkit.
Do You Really Know AbortController? is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:
Multi-Language Support
Deploy unlimited projects for free
Unbeatable Cost Efficiency
Streamlined Developer Experience
Effortless Scalability and High Performance
Explore more in the Documentation!
Follow us on X: @Do You Really Know AbortController?HQ
Read on our blog
The above is the detailed content of Do You Really Know AbortController?. For more information, please follow other related articles on the PHP Chinese website!